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 * XYStepAreaRenderer.java
029 * -----------------------
030 * (C) Copyright 2003-2017, by Matthias Rose and Contributors.
031 *
032 * Original Author:  Matthias Rose (based on XYAreaRenderer.java);
033 * Contributor(s):   David Gilbert (for Object Refinery Limited);
034 *                   Lukasz Rzeszotarski;
035 *
036 * Changes:
037 * --------
038 * 07-Oct-2003 : Version 1, contributed by Matthias Rose (DG);
039 * 10-Feb-2004 : Added some getter and setter methods (DG);
040 * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState.  Renamed
041 *               XYToolTipGenerator --> XYItemLabelGenerator (DG);
042 * 15-Jul-2004 : Switched getX() with getXValue() and getY() with
043 *               getYValue() (DG);
044 * 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG);
045 * 06-Jul-2005 : Renamed get/setPlotShapes() --> get/setShapesVisible() (DG);
046 * ------------- JFREECHART 1.0.x ---------------------------------------------
047 * 06-Jul-2006 : Modified to call dataset methods that return double
048 *               primitives only (DG);
049 * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG);
050 * 14-Feb-2007 : Added equals() method override (DG);
051 * 04-May-2007 : Set processVisibleItemsOnly flag to false (DG);
052 * 14-May-2008 : Call addEntity() from within drawItem() (DG);
053 * 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
054 * 05-Dec-2013 : Added setStepPoint() method (LR);
055 * 18-Feb-2017 : Updates for crosshairs (bug #36) (DG);
056 *
057 */
058
059package org.jfree.chart.renderer.xy;
060
061import java.awt.Graphics2D;
062import java.awt.Paint;
063import java.awt.Polygon;
064import java.awt.Shape;
065import java.awt.Stroke;
066import java.awt.geom.Rectangle2D;
067import java.io.Serializable;
068
069import org.jfree.chart.axis.ValueAxis;
070import org.jfree.chart.entity.EntityCollection;
071import org.jfree.chart.event.RendererChangeEvent;
072import org.jfree.chart.labels.XYToolTipGenerator;
073import org.jfree.chart.plot.CrosshairState;
074import org.jfree.chart.plot.PlotOrientation;
075import org.jfree.chart.plot.PlotRenderingInfo;
076import org.jfree.chart.plot.XYPlot;
077import org.jfree.chart.urls.XYURLGenerator;
078import org.jfree.chart.util.PublicCloneable;
079import org.jfree.chart.util.ShapeUtils;
080import org.jfree.data.xy.XYDataset;
081
082/**
083 * A step chart renderer that fills the area between the step and the x-axis.
084 * The example shown here is generated by the
085 * {@code XYStepAreaRendererDemo1.java} program included in the JFreeChart
086 * demo collection:
087 * <br><br>
088 * <img src="../../../../../images/XYStepAreaRendererSample.png"
089 * alt="XYStepAreaRendererSample.png">
090 */
091public class XYStepAreaRenderer extends AbstractXYItemRenderer
092        implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
093
094    /** For serialization. */
095    private static final long serialVersionUID = -7311560779702649635L;
096
097    /** Useful constant for specifying the type of rendering (shapes only). */
098    public static final int SHAPES = 1;
099
100    /** Useful constant for specifying the type of rendering (area only). */
101    public static final int AREA = 2;
102
103    /**
104     * Useful constant for specifying the type of rendering (area and shapes).
105     */
106    public static final int AREA_AND_SHAPES = 3;
107
108    /** A flag indicating whether or not shapes are drawn at each XY point. */
109    private boolean shapesVisible;
110
111    /** A flag that controls whether or not shapes are filled for ALL series. */
112    private boolean shapesFilled;
113
114    /** A flag indicating whether or not Area are drawn at each XY point. */
115    private boolean plotArea;
116
117    /** A flag that controls whether or not the outline is shown. */
118    private boolean showOutline;
119
120    /** Area of the complete series */
121    protected transient Polygon pArea = null;
122
123    /**
124     * The value on the range axis which defines the 'lower' border of the
125     * area.
126     */
127    private double rangeBase;
128    
129    /**
130     * The factor (from 0.0 to 1.0) that determines the position of the
131     * step.
132     *
133     * @since 1.0.18.
134     */
135    private double stepPoint;
136
137    /**
138     * Constructs a new renderer.
139     */
140    public XYStepAreaRenderer() {
141        this(AREA);
142    }
143
144    /**
145     * Constructs a new renderer.
146     *
147     * @param type  the type of the renderer.
148     */
149    public XYStepAreaRenderer(int type) {
150        this(type, null, null);
151    }
152
153    /**
154     * Constructs a new renderer.
155     * <p>
156     * To specify the type of renderer, use one of the constants:
157     * AREA, SHAPES or AREA_AND_SHAPES.
158     *
159     * @param type  the type of renderer.
160     * @param toolTipGenerator  the tool tip generator to use
161     *                          ({@code null} permitted).
162     * @param urlGenerator  the URL generator ({@code null} permitted).
163     */
164    public XYStepAreaRenderer(int type, XYToolTipGenerator toolTipGenerator,
165            XYURLGenerator urlGenerator) {
166        super();
167        setDefaultToolTipGenerator(toolTipGenerator);
168        setURLGenerator(urlGenerator);
169
170        if (type == AREA) {
171            this.plotArea = true;
172        }
173        else if (type == SHAPES) {
174            this.shapesVisible = true;
175        }
176        else if (type == AREA_AND_SHAPES) {
177            this.plotArea = true;
178            this.shapesVisible = true;
179        }
180        this.showOutline = false;
181        this.stepPoint = 1.0;
182    }
183
184    /**
185     * Returns a flag that controls whether or not outlines of the areas are
186     * drawn.
187     *
188     * @return The flag.
189     *
190     * @see #setOutline(boolean)
191     */
192    public boolean isOutline() {
193        return this.showOutline;
194    }
195
196    /**
197     * Sets a flag that controls whether or not outlines of the areas are
198     * drawn, and sends a {@link RendererChangeEvent} to all registered
199     * listeners.
200     *
201     * @param show  the flag.
202     *
203     * @see #isOutline()
204     */
205    public void setOutline(boolean show) {
206        this.showOutline = show;
207        fireChangeEvent();
208    }
209
210    /**
211     * Returns true if shapes are being plotted by the renderer.
212     *
213     * @return {@code true} if shapes are being plotted by the renderer.
214     *
215     * @see #setShapesVisible(boolean)
216     */
217    public boolean getShapesVisible() {
218        return this.shapesVisible;
219    }
220
221    /**
222     * Sets the flag that controls whether or not shapes are displayed for each
223     * data item, and sends a {@link RendererChangeEvent} to all registered
224     * listeners.
225     *
226     * @param flag  the flag.
227     *
228     * @see #getShapesVisible()
229     */
230    public void setShapesVisible(boolean flag) {
231        this.shapesVisible = flag;
232        fireChangeEvent();
233    }
234
235    /**
236     * Returns the flag that controls whether or not the shapes are filled.
237     *
238     * @return A boolean.
239     *
240     * @see #setShapesFilled(boolean)
241     */
242    public boolean isShapesFilled() {
243        return this.shapesFilled;
244    }
245
246    /**
247     * Sets the 'shapes filled' for ALL series and sends a
248     * {@link RendererChangeEvent} to all registered listeners.
249     *
250     * @param filled  the flag.
251     *
252     * @see #isShapesFilled()
253     */
254    public void setShapesFilled(boolean filled) {
255        this.shapesFilled = filled;
256        fireChangeEvent();
257    }
258
259    /**
260     * Returns true if Area is being plotted by the renderer.
261     *
262     * @return {@code true} if Area is being plotted by the renderer.
263     *
264     * @see #setPlotArea(boolean)
265     */
266    public boolean getPlotArea() {
267        return this.plotArea;
268    }
269
270    /**
271     * Sets a flag that controls whether or not areas are drawn for each data
272     * item and sends a {@link RendererChangeEvent} to all registered
273     * listeners.
274     *
275     * @param flag  the flag.
276     *
277     * @see #getPlotArea()
278     */
279    public void setPlotArea(boolean flag) {
280        this.plotArea = flag;
281        fireChangeEvent();
282    }
283
284    /**
285     * Returns the value on the range axis which defines the 'lower' border of
286     * the area.
287     *
288     * @return {@code double} the value on the range axis which defines
289     *         the 'lower' border of the area.
290     *
291     * @see #setRangeBase(double)
292     */
293    public double getRangeBase() {
294        return this.rangeBase;
295    }
296
297    /**
298     * Sets the value on the range axis which defines the default border of the
299     * area, and sends a {@link RendererChangeEvent} to all registered
300     * listeners.  E.g. setRangeBase(Double.NEGATIVE_INFINITY) lets areas always
301     * reach the lower border of the plotArea.
302     *
303     * @param val  the value on the range axis which defines the default border
304     *             of the area.
305     *
306     * @see #getRangeBase()
307     */
308    public void setRangeBase(double val) {
309        this.rangeBase = val;
310        fireChangeEvent();
311    }
312
313    /**
314     * Returns the fraction of the domain position between two points on which
315     * the step is drawn.  The default is 1.0d, which means the step is drawn
316     * at the domain position of the second`point. If the stepPoint is 0.5d the
317     * step is drawn at half between the two points.
318     *
319     * @return The fraction of the domain position between two points where the
320     *         step is drawn.
321     *
322     * @see #setStepPoint(double)
323     *
324     * @since 1.0.18
325     */
326    public double getStepPoint() {
327        return stepPoint;
328    }
329     
330    /**
331     * Sets the step point and sends a {@link RendererChangeEvent} to all
332     * registered listeners.
333     *
334     * @param stepPoint  the step point (in the range 0.0 to 1.0)
335     *
336     * @see #getStepPoint()
337     *
338     * @since 1.0.18
339     */
340    public void setStepPoint(double stepPoint) {
341        if (stepPoint < 0.0d || stepPoint > 1.0d) {
342             throw new IllegalArgumentException(
343                     "Requires stepPoint in [0.0;1.0]");
344        }
345        this.stepPoint = stepPoint;
346        fireChangeEvent();
347    }
348
349    /**
350     * Initialises the renderer.  Here we calculate the Java2D y-coordinate for
351     * zero, since all the bars have their bases fixed at zero.
352     *
353     * @param g2  the graphics device.
354     * @param dataArea  the area inside the axes.
355     * @param plot  the plot.
356     * @param data  the data.
357     * @param info  an optional info collection object to return data back to
358     *              the caller.
359     *
360     * @return The number of passes required by the renderer.
361     */
362    @Override
363    public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea,
364            XYPlot plot, XYDataset data, PlotRenderingInfo info) {
365
366        XYItemRendererState state = super.initialise(g2, dataArea, plot, data,
367                info);
368        // disable visible items optimisation - it doesn't work for this
369        // renderer...
370        state.setProcessVisibleItemsOnly(false);
371        return state;
372
373    }
374
375    /**
376     * Draws the visual representation of a single data item.
377     *
378     * @param g2  the graphics device.
379     * @param state  the renderer state.
380     * @param dataArea  the area within which the data is being drawn.
381     * @param info  collects information about the drawing.
382     * @param plot  the plot (can be used to obtain standard color information
383     *              etc).
384     * @param domainAxis  the domain axis.
385     * @param rangeAxis  the range axis.
386     * @param dataset  the dataset.
387     * @param series  the series index (zero-based).
388     * @param item  the item index (zero-based).
389     * @param crosshairState  crosshair information for the plot
390     *                        ({@code null} permitted).
391     * @param pass  the pass index.
392     */
393    @Override
394    public void drawItem(Graphics2D g2, XYItemRendererState state, 
395            Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
396            ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
397            int series, int item, CrosshairState crosshairState, int pass) {
398
399        PlotOrientation orientation = plot.getOrientation();
400
401        // Get the item count for the series, so that we can know which is the
402        // end of the series.
403        int itemCount = dataset.getItemCount(series);
404
405        Paint paint = getItemPaint(series, item);
406        Stroke seriesStroke = getItemStroke(series, item);
407        g2.setPaint(paint);
408        g2.setStroke(seriesStroke);
409
410        // get the data point...
411        double x1 = dataset.getXValue(series, item);
412        double y1 = dataset.getYValue(series, item);
413        double x = x1;
414        double y = Double.isNaN(y1) ? getRangeBase() : y1;
415        double transX1 = domainAxis.valueToJava2D(x, dataArea,
416                plot.getDomainAxisEdge());
417        double transY1 = rangeAxis.valueToJava2D(y, dataArea,
418                plot.getRangeAxisEdge());
419
420        // avoid possible sun.dc.pr.PRException: endPath: bad path
421        transY1 = restrictValueToDataArea(transY1, plot, dataArea);
422
423        if (this.pArea == null && !Double.isNaN(y1)) {
424
425            // Create a new Area for the series
426            this.pArea = new Polygon();
427
428            // start from Y = rangeBase
429            double transY2 = rangeAxis.valueToJava2D(getRangeBase(), dataArea,
430                    plot.getRangeAxisEdge());
431
432            // avoid possible sun.dc.pr.PRException: endPath: bad path
433            transY2 = restrictValueToDataArea(transY2, plot, dataArea);
434
435            // The first point is (x, this.baseYValue)
436            if (orientation == PlotOrientation.VERTICAL) {
437                this.pArea.addPoint((int) transX1, (int) transY2);
438            }
439            else if (orientation == PlotOrientation.HORIZONTAL) {
440                this.pArea.addPoint((int) transY2, (int) transX1);
441            }
442        }
443
444        double transX0;
445        double transY0;
446
447        double x0;
448        double y0;
449        if (item > 0) {
450            // get the previous data point...
451            x0 = dataset.getXValue(series, item - 1);
452            y0 = Double.isNaN(y1) ? y1 : dataset.getYValue(series, item - 1);
453
454            x = x0;
455            y = Double.isNaN(y0) ? getRangeBase() : y0;
456            transX0 = domainAxis.valueToJava2D(x, dataArea,
457                    plot.getDomainAxisEdge());
458            transY0 = rangeAxis.valueToJava2D(y, dataArea,
459                    plot.getRangeAxisEdge());
460
461            // avoid possible sun.dc.pr.PRException: endPath: bad path
462            transY0 = restrictValueToDataArea(transY0, plot, dataArea);
463
464            if (Double.isNaN(y1)) {
465                // NULL value -> insert point on base line
466                // instead of 'step point'
467                transX1 = transX0;
468                transY0 = transY1;
469            }
470            if (transY0 != transY1) {
471                // not just a horizontal bar but need to perform a 'step'.
472                double transXs = transX0 + (getStepPoint()
473                        * (transX1 - transX0));
474                if (orientation == PlotOrientation.VERTICAL) {
475                    this.pArea.addPoint((int) transXs, (int) transY0);
476                    this.pArea.addPoint((int) transXs, (int) transY1);
477                }
478                else if (orientation == PlotOrientation.HORIZONTAL) {
479                    this.pArea.addPoint((int) transY0, (int) transXs);
480                    this.pArea.addPoint((int) transY1, (int) transXs);
481                }
482            }
483        }
484
485        Shape shape = null;
486        if (!Double.isNaN(y1)) {
487            // Add each point to Area (x, y)
488            if (orientation == PlotOrientation.VERTICAL) {
489                this.pArea.addPoint((int) transX1, (int) transY1);
490            }
491            else if (orientation == PlotOrientation.HORIZONTAL) {
492                this.pArea.addPoint((int) transY1, (int) transX1);
493            }
494
495            if (getShapesVisible()) {
496                shape = getItemShape(series, item);
497                if (orientation == PlotOrientation.VERTICAL) {
498                    shape = ShapeUtils.createTranslatedShape(shape,
499                            transX1, transY1);
500                }
501                else if (orientation == PlotOrientation.HORIZONTAL) {
502                    shape = ShapeUtils.createTranslatedShape(shape,
503                            transY1, transX1);
504                }
505                if (isShapesFilled()) {
506                    g2.fill(shape);
507                }
508                else {
509                    g2.draw(shape);
510                }
511            }
512            else {
513                if (orientation == PlotOrientation.VERTICAL) {
514                    shape = new Rectangle2D.Double(transX1 - 2, transY1 - 2,
515                            4.0, 4.0);
516                } else if (orientation == PlotOrientation.HORIZONTAL) {
517                    shape = new Rectangle2D.Double(transY1 - 2, transX1 - 2,
518                            4.0, 4.0);
519                }
520            }
521        }
522
523        // Check if the item is the last item for the series or if it
524        // is a NULL value and number of items > 0.  We can't draw an area for
525        // a single point.
526        if (getPlotArea() && item > 0 && this.pArea != null
527                          && (item == (itemCount - 1) || Double.isNaN(y1))) {
528
529            double transY2 = rangeAxis.valueToJava2D(getRangeBase(), dataArea,
530                    plot.getRangeAxisEdge());
531
532            // avoid possible sun.dc.pr.PRException: endPath: bad path
533            transY2 = restrictValueToDataArea(transY2, plot, dataArea);
534
535            if (orientation == PlotOrientation.VERTICAL) {
536                // Add the last point (x,0)
537                this.pArea.addPoint((int) transX1, (int) transY2);
538            }
539            else if (orientation == PlotOrientation.HORIZONTAL) {
540                // Add the last point (x,0)
541                this.pArea.addPoint((int) transY2, (int) transX1);
542            }
543
544            // fill the polygon
545            g2.fill(this.pArea);
546
547            // draw an outline around the Area.
548            if (isOutline()) {
549                g2.setStroke(plot.getOutlineStroke());
550                g2.setPaint(plot.getOutlinePaint());
551                g2.draw(this.pArea);
552            }
553
554            // start new area when needed (see above)
555            this.pArea = null;
556        }
557
558        // do we need to update the crosshair values?
559        if (!Double.isNaN(y1)) {
560            int datasetIndex = plot.indexOf(dataset);
561            updateCrosshairValues(crosshairState, x1, y1, datasetIndex,
562                    transX1, transY1, orientation);
563        }
564
565        // collect entity and tool tip information...
566        EntityCollection entities = state.getEntityCollection();
567        if (entities != null && shape != null) {
568            addEntity(entities, shape, dataset, series, item, 0.0, 0.0);
569        }
570    }
571
572    /**
573     * Tests this renderer for equality with an arbitrary object.
574     *
575     * @param obj  the object ({@code null} permitted).
576     *
577     * @return A boolean.
578     */
579    @Override
580    public boolean equals(Object obj) {
581        if (obj == this) {
582            return true;
583        }
584        if (!(obj instanceof XYStepAreaRenderer)) {
585            return false;
586        }
587        XYStepAreaRenderer that = (XYStepAreaRenderer) obj;
588        if (this.showOutline != that.showOutline) {
589            return false;
590        }
591        if (this.shapesVisible != that.shapesVisible) {
592            return false;
593        }
594        if (this.shapesFilled != that.shapesFilled) {
595            return false;
596        }
597        if (this.plotArea != that.plotArea) {
598            return false;
599        }
600        if (this.rangeBase != that.rangeBase) {
601            return false;
602        }
603        if (this.stepPoint != that.stepPoint) {
604            return false;
605        }
606        return super.equals(obj);
607    }
608
609    /**
610     * Returns a clone of the renderer.
611     *
612     * @return A clone.
613     *
614     * @throws CloneNotSupportedException  if the renderer cannot be cloned.
615     */
616    @Override
617    public Object clone() throws CloneNotSupportedException {
618        return super.clone();
619    }
620
621    /**
622     * Helper method which returns a value if it lies
623     * inside the visible dataArea and otherwise the corresponding
624     * coordinate on the border of the dataArea. The PlotOrientation
625     * is taken into account.
626     * Useful to avoid possible sun.dc.pr.PRException: endPath: bad path
627     * which occurs when trying to draw lines/shapes which in large part
628     * lie outside of the visible dataArea.
629     *
630     * @param value the value which shall be
631     * @param dataArea  the area within which the data is being drawn.
632     * @param plot  the plot (can be used to obtain standard color
633     *              information etc).
634     * @return {@code double} value inside the data area.
635     */
636    protected static double restrictValueToDataArea(double value,
637                                                    XYPlot plot,
638                                                    Rectangle2D dataArea) {
639        double min = 0;
640        double max = 0;
641        if (plot.getOrientation() == PlotOrientation.VERTICAL) {
642            min = dataArea.getMinY();
643            max = dataArea.getMaxY();
644        }
645        else if (plot.getOrientation() ==  PlotOrientation.HORIZONTAL) {
646            min = dataArea.getMinX();
647            max = dataArea.getMaxX();
648        }
649        if (value < min) {
650            value = min;
651        }
652        else if (value > max) {
653            value = max;
654        }
655        return value;
656    }
657
658}