001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2017, 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 * XYStepRenderer.java
029 * -------------------
030 * (C) Copyright 2002-2017, by Roger Studner and Contributors.
031 *
032 * Original Author:  Roger Studner;
033 * Contributor(s):   David Gilbert (for Object Refinery Limited);
034 *                   Matthias Rose;
035 *                   Gerald Struck (fix for bug 1569094);
036 *                   Ulrich Voigt (patch 1874890);
037 *                   Martin Hoeller (contribution to patch 1874890);
038 *                   Matthias Noebl (for Cropster GmbH);
039 *
040 * Changes
041 * -------
042 * 13-May-2002 : Version 1, contributed by Roger Studner (DG);
043 * 25-Jun-2002 : Updated import statements (DG);
044 * 22-Jul-2002 : Added check for null data items (DG);
045 * 25-Mar-2003 : Implemented Serializable (DG);
046 * 01-May-2003 : Modified drawItem() method signature (DG);
047 * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG);
048 * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
049 * 28-Oct-2003 : Added tooltips, code contributed by Matthias Rose
050 *               (RFE 824857) (DG);
051 * 10-Feb-2004 : Removed working line (use line from state object instead) (DG);
052 * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState.  Renamed
053 *               XYToolTipGenerator --> XYItemLabelGenerator (DG);
054 * 19-Jan-2005 : Now accesses only primitives from dataset (DG);
055 * 15-Mar-2005 : Fix silly bug in drawItem() method (DG);
056 * 19-Sep-2005 : Extend XYLineAndShapeRenderer (fixes legend shapes), added
057 *               support for series visibility, and use getDefaultEntityRadius()
058 *               for entity hotspot size (DG);
059 * ------------- JFREECHART 1.0.x ---------------------------------------------
060 * 15-Jun-2006 : Added basic support for item labels (DG);
061 * 11-Oct-2006 : Fixed rendering with horizontal orientation (see bug 1569094),
062 *               thanks to Gerald Struck (DG);
063 * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG);
064 * 14-Feb-2008 : Applied patch 1874890 by Ulrich Voigt (with contribution from
065 *               Martin Hoeller) (DG);
066 * 14-May-2008 : Call addEntity() in drawItem() (DG);
067 * 24-Sep-2008 : Fixed bug 2113627 by utilising second pass to draw item
068 *               labels (DG);
069 * 29-Feb-2016 : Improved performance by only drawing visible lines (MN);
070 * 18-Feb-2017 : Updates for crosshairs (bug #36) (DG);
071 *
072 */
073
074package org.jfree.chart.renderer.xy;
075
076import java.awt.Graphics2D;
077import java.awt.Paint;
078import java.awt.Stroke;
079import java.awt.geom.Line2D;
080import java.awt.geom.Rectangle2D;
081import java.io.Serializable;
082
083import org.jfree.chart.HashUtils;
084import org.jfree.chart.axis.ValueAxis;
085import org.jfree.chart.entity.EntityCollection;
086import org.jfree.chart.event.RendererChangeEvent;
087import org.jfree.chart.labels.XYToolTipGenerator;
088import org.jfree.chart.plot.CrosshairState;
089import org.jfree.chart.plot.PlotOrientation;
090import org.jfree.chart.plot.PlotRenderingInfo;
091import org.jfree.chart.plot.XYPlot;
092import org.jfree.chart.ui.RectangleEdge;
093import org.jfree.chart.urls.XYURLGenerator;
094import org.jfree.chart.util.LineUtils;
095import org.jfree.chart.util.PublicCloneable;
096import org.jfree.data.xy.XYDataset;
097
098/**
099 * Line/Step item renderer for an {@link XYPlot}.  This class draws lines
100 * between data points, only allowing horizontal or vertical lines (steps).
101 * The example shown here is generated by the
102 * {@code XYStepRendererDemo1.java} program included in the JFreeChart
103 * demo collection:
104 * <br><br>
105 * <img src="../../../../../images/XYStepRendererSample.png"
106 * alt="XYStepRendererSample.png">
107 */
108public class XYStepRenderer extends XYLineAndShapeRenderer
109        implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
110
111    /** For serialization. */
112    private static final long serialVersionUID = -8918141928884796108L;
113
114    /**
115     * The factor (from 0.0 to 1.0) that determines the position of the
116     * step.
117     *
118     * @since 1.0.10.
119     */
120    private double stepPoint = 1.0d;
121
122    /**
123     * Constructs a new renderer with no tooltip or URL generation.
124     */
125    public XYStepRenderer() {
126        this(null, null);
127    }
128
129    /**
130     * Constructs a new renderer with the specified tool tip and URL
131     * generators.
132     *
133     * @param toolTipGenerator  the item label generator ({@code null}
134     *     permitted).
135     * @param urlGenerator  the URL generator ({@code null} permitted).
136     */
137    public XYStepRenderer(XYToolTipGenerator toolTipGenerator,
138                          XYURLGenerator urlGenerator) {
139        super();
140        setDefaultToolTipGenerator(toolTipGenerator);
141        setURLGenerator(urlGenerator);
142        setDefaultShapesVisible(false);
143    }
144
145    /**
146     * Returns the fraction of the domain position between two points on which
147     * the step is drawn.  The default is 1.0d, which means the step is drawn
148     * at the domain position of the second`point. If the stepPoint is 0.5d the
149     * step is drawn at half between the two points.
150     *
151     * @return The fraction of the domain position between two points where the
152     *         step is drawn.
153     *
154     * @see #setStepPoint(double)
155     *
156     * @since 1.0.10
157     */
158    public double getStepPoint() {
159        return this.stepPoint;
160    }
161
162    /**
163     * Sets the step point and sends a {@link RendererChangeEvent} to all
164     * registered listeners.
165     *
166     * @param stepPoint  the step point (in the range 0.0 to 1.0)
167     *
168     * @see #getStepPoint()
169     *
170     * @since 1.0.10
171     */
172    public void setStepPoint(double stepPoint) {
173        if (stepPoint < 0.0d || stepPoint > 1.0d) {
174            throw new IllegalArgumentException(
175                    "Requires stepPoint in [0.0;1.0]");
176        }
177        this.stepPoint = stepPoint;
178        fireChangeEvent();
179    }
180
181    /**
182     * Draws the visual representation of a single data item.
183     *
184     * @param g2  the graphics device.
185     * @param state  the renderer state.
186     * @param dataArea  the area within which the data is being drawn.
187     * @param info  collects information about the drawing.
188     * @param plot  the plot (can be used to obtain standard color
189     *              information etc).
190     * @param domainAxis  the domain axis.
191     * @param rangeAxis  the vertical axis.
192     * @param dataset  the dataset.
193     * @param series  the series index (zero-based).
194     * @param item  the item index (zero-based).
195     * @param crosshairState  crosshair information for the plot
196     *                        ({@code null} permitted).
197     * @param pass  the pass index.
198     */
199    @Override
200    public void drawItem(Graphics2D g2, XYItemRendererState state,
201            Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
202            ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
203            int series, int item, CrosshairState crosshairState, int pass) {
204
205        // do nothing if item is not visible
206        if (!getItemVisible(series, item)) {
207            return;
208        }
209
210        PlotOrientation orientation = plot.getOrientation();
211
212        Paint seriesPaint = getItemPaint(series, item);
213        Stroke seriesStroke = getItemStroke(series, item);
214        g2.setPaint(seriesPaint);
215        g2.setStroke(seriesStroke);
216
217        // get the data point...
218        double x1 = dataset.getXValue(series, item);
219        double y1 = dataset.getYValue(series, item);
220
221        RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
222        RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
223        double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
224        double transY1 = (Double.isNaN(y1) ? Double.NaN
225                : rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation));
226
227        if (pass == 0 && item > 0) {
228            // get the previous data point...
229            double x0 = dataset.getXValue(series, item - 1);
230            double y0 = dataset.getYValue(series, item - 1);
231            double transX0 = domainAxis.valueToJava2D(x0, dataArea,
232                    xAxisLocation);
233            double transY0 = (Double.isNaN(y0) ? Double.NaN
234                    : rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation));
235
236            if (orientation == PlotOrientation.HORIZONTAL) {
237                if (transY0 == transY1) {
238                    // this represents the situation
239                    // for drawing a horizontal bar.
240                    drawLine(g2, state.workingLine, transY0, transX0, transY1,
241                            transX1, dataArea);
242                }
243                else {  //this handles the need to perform a 'step'.
244
245                    // calculate the step point
246                    double transXs = transX0 + (getStepPoint()
247                            * (transX1 - transX0));
248                    drawLine(g2, state.workingLine, transY0, transX0, transY0,
249                            transXs, dataArea);
250                    drawLine(g2, state.workingLine, transY0, transXs, transY1,
251                            transXs, dataArea);
252                    drawLine(g2, state.workingLine, transY1, transXs, transY1,
253                            transX1, dataArea);
254                }
255            }
256            else if (orientation == PlotOrientation.VERTICAL) {
257                if (transY0 == transY1) { // this represents the situation
258                                          // for drawing a horizontal bar.
259                    drawLine(g2, state.workingLine, transX0, transY0, transX1,
260                            transY1, dataArea);
261                }
262                else {  //this handles the need to perform a 'step'.
263                    // calculate the step point
264                    double transXs = transX0 + (getStepPoint()
265                            * (transX1 - transX0));
266                    drawLine(g2, state.workingLine, transX0, transY0, transXs,
267                            transY0, dataArea);
268                    drawLine(g2, state.workingLine, transXs, transY0, transXs,
269                            transY1, dataArea);
270                    drawLine(g2, state.workingLine, transXs, transY1, transX1,
271                            transY1, dataArea);
272                }
273            }
274
275            // submit this data item as a candidate for the crosshair point
276            int datasetIndex = plot.indexOf(dataset);
277            updateCrosshairValues(crosshairState, x1, y1, datasetIndex,
278                    transX1, transY1, orientation);
279
280            // collect entity and tool tip information...
281            EntityCollection entities = state.getEntityCollection();
282            if (entities != null) {
283                if (orientation == PlotOrientation.HORIZONTAL) {
284                    addEntity(entities, null, dataset, series, item, transY1,
285                            transX1);
286                } else {
287                    addEntity(entities, null, dataset, series, item, transX1,
288                            transY1);
289                }
290            }
291
292        }
293
294        if (pass == 1) {
295            // draw the item label if there is one...
296            if (isItemLabelVisible(series, item)) {
297                double xx = transX1;
298                double yy = transY1;
299                if (orientation == PlotOrientation.HORIZONTAL) {
300                    xx = transY1;
301                    yy = transX1;
302                }
303                drawItemLabel(g2, orientation, dataset, series, item, xx, yy,
304                        (y1 < 0.0));
305            }
306        }
307    }
308
309    /**
310     * A utility method that draws a line but only if none of the coordinates
311     * are NaN values.
312     *
313     * @param g2  the graphics target.
314     * @param line  the line object.
315     * @param x0  the x-coordinate for the starting point of the line.
316     * @param y0  the y-coordinate for the starting point of the line.
317     * @param x1  the x-coordinate for the ending point of the line.
318     * @param y1  the y-coordinate for the ending point of the line.
319     */
320    private void drawLine(Graphics2D g2, Line2D line, double x0, double y0,
321            double x1, double y1, Rectangle2D dataArea) {
322        if (Double.isNaN(x0) || Double.isNaN(x1) || Double.isNaN(y0)
323                || Double.isNaN(y1)) {
324            return;
325        }
326        line.setLine(x0, y0, x1, y1);
327        boolean visible = LineUtils.clipLine(line, dataArea);
328        if (visible) {
329            g2.draw(line);
330        }
331    }
332
333    /**
334     * Tests this renderer for equality with an arbitrary object.
335     *
336     * @param obj  the object ({@code null} permitted).
337     *
338     * @return A boolean.
339     */
340    @Override
341    public boolean equals(Object obj) {
342        if (obj == this) {
343            return true;
344        }
345        if (!(obj instanceof XYLineAndShapeRenderer)) {
346            return false;
347        }
348        XYStepRenderer that = (XYStepRenderer) obj;
349        if (this.stepPoint != that.stepPoint) {
350            return false;
351        }
352        return super.equals(obj);
353    }
354
355    /**
356     * Returns a hash code for this instance.
357     *
358     * @return A hash code.
359     */
360    @Override
361    public int hashCode() {
362        return HashUtils.hashCode(super.hashCode(), this.stepPoint);
363    }
364
365    /**
366     * Returns a clone of the renderer.
367     *
368     * @return A clone.
369     *
370     * @throws CloneNotSupportedException  if the renderer cannot be cloned.
371     */
372    @Override
373    public Object clone() throws CloneNotSupportedException {
374        return super.clone();
375    }
376
377}