001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, 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 * HighLowRenderer.java
029 * --------------------
030 * (C) Copyright 2001-2016, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Richard Atkinson;
034 *                   Christian W. Zuckschwerdt;
035 *
036 * Changes
037 * -------
038 * 13-Dec-2001 : Version 1 (DG);
039 * 23-Jan-2002 : Added DrawInfo parameter to drawItem() method (DG);
040 * 28-Mar-2002 : Added a property change listener mechanism so that renderers
041 *               no longer need to be immutable (DG);
042 * 09-Apr-2002 : Removed translatedRangeZero from the drawItem() method, and
043 *               changed the return type of the drawItem method to void,
044 *               reflecting a change in the XYItemRenderer interface.  Added
045 *               tooltip code to drawItem() method (DG);
046 * 05-Aug-2002 : Small modification to drawItem method to support URLs for
047 *               HTML image maps (RA);
048 * 25-Mar-2003 : Implemented Serializable (DG);
049 * 01-May-2003 : Modified drawItem() method signature (DG);
050 * 30-Jul-2003 : Modified entity constructor (CZ);
051 * 31-Jul-2003 : Deprecated constructor (DG);
052 * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG);
053 * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
054 * 29-Jan-2004 : Fixed bug (882392) when rendering with
055 *               PlotOrientation.HORIZONTAL (DG);
056 * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState.  Renamed
057 *               XYToolTipGenerator --> XYItemLabelGenerator (DG);
058 * 15-Jul-2004 : Switched getX() with getXValue() and getY() with
059 *               getYValue() (DG);
060 * 01-Nov-2005 : Added optional openTickPaint and closeTickPaint settings (DG);
061 * ------------- JFREECHART 1.0.0 ---------------------------------------------
062 * 06-Jul-2006 : Replace dataset methods getX() --> getXValue() (DG);
063 * 08-Apr-2008 : Added findRangeBounds() override (DG);
064 * 29-Apr-2008 : Added tickLength field (DG);
065 * 25-Sep-2008 : Check for non-null entity collection (DG);
066 *
067 */
068
069package org.jfree.chart.renderer.xy;
070
071import java.awt.Graphics2D;
072import java.awt.Paint;
073import java.awt.Shape;
074import java.awt.Stroke;
075import java.awt.geom.Line2D;
076import java.awt.geom.Rectangle2D;
077import java.io.IOException;
078import java.io.ObjectInputStream;
079import java.io.ObjectOutputStream;
080import java.io.Serializable;
081
082import org.jfree.chart.axis.ValueAxis;
083import org.jfree.chart.entity.EntityCollection;
084import org.jfree.chart.event.RendererChangeEvent;
085import org.jfree.chart.plot.CrosshairState;
086import org.jfree.chart.plot.PlotOrientation;
087import org.jfree.chart.plot.PlotRenderingInfo;
088import org.jfree.chart.plot.XYPlot;
089import org.jfree.chart.ui.RectangleEdge;
090import org.jfree.chart.util.PaintUtils;
091import org.jfree.chart.util.PublicCloneable;
092import org.jfree.chart.util.SerialUtils;
093import org.jfree.data.Range;
094import org.jfree.data.general.DatasetUtils;
095import org.jfree.data.xy.OHLCDataset;
096import org.jfree.data.xy.XYDataset;
097
098/**
099 * A renderer that draws high/low/open/close markers on an {@link XYPlot}
100 * (requires a {@link OHLCDataset}).  This renderer does not include code to
101 * calculate the crosshair point for the plot.
102 *
103 * The example shown here is generated by the {@code HighLowChartDemo1.java} 
104 * program included in the JFreeChart Demo Collection:
105 * <br><br>
106 * <img src="../../../../../images/HighLowRendererSample.png"
107 * alt="HighLowRendererSample.png">
108 */
109public class HighLowRenderer extends AbstractXYItemRenderer
110        implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
111
112    /** For serialization. */
113    private static final long serialVersionUID = -8135673815876552516L;
114
115    /** A flag that controls whether the open ticks are drawn. */
116    private boolean drawOpenTicks;
117
118    /** A flag that controls whether the close ticks are drawn. */
119    private boolean drawCloseTicks;
120
121    /**
122     * The paint used for the open ticks (if {@code null}, the series
123     * paint is used instead).
124     */
125    private transient Paint openTickPaint;
126
127    /**
128     * The paint used for the close ticks (if {@code null}, the series
129     * paint is used instead).
130     */
131    private transient Paint closeTickPaint;
132
133    /**
134     * The tick length (in Java2D units).
135     *
136     * @since 1.0.10
137     */
138    private double tickLength;
139
140    /**
141     * The default constructor.
142     */
143    public HighLowRenderer() {
144        super();
145        this.drawOpenTicks = true;
146        this.drawCloseTicks = true;
147        this.tickLength = 2.0;
148    }
149
150    /**
151     * Returns the flag that controls whether open ticks are drawn.
152     *
153     * @return A boolean.
154     *
155     * @see #getDrawCloseTicks()
156     * @see #setDrawOpenTicks(boolean)
157     */
158    public boolean getDrawOpenTicks() {
159        return this.drawOpenTicks;
160    }
161
162    /**
163     * Sets the flag that controls whether open ticks are drawn, and sends a
164     * {@link RendererChangeEvent} to all registered listeners.
165     *
166     * @param draw  the flag.
167     *
168     * @see #getDrawOpenTicks()
169     */
170    public void setDrawOpenTicks(boolean draw) {
171        this.drawOpenTicks = draw;
172        fireChangeEvent();
173    }
174
175    /**
176     * Returns the flag that controls whether close ticks are drawn.
177     *
178     * @return A boolean.
179     *
180     * @see #getDrawOpenTicks()
181     * @see #setDrawCloseTicks(boolean)
182     */
183    public boolean getDrawCloseTicks() {
184        return this.drawCloseTicks;
185    }
186
187    /**
188     * Sets the flag that controls whether close ticks are drawn, and sends a
189     * {@link RendererChangeEvent} to all registered listeners.
190     *
191     * @param draw  the flag.
192     *
193     * @see #getDrawCloseTicks()
194     */
195    public void setDrawCloseTicks(boolean draw) {
196        this.drawCloseTicks = draw;
197        fireChangeEvent();
198    }
199
200    /**
201     * Returns the paint used to draw the ticks for the open values.
202     *
203     * @return The paint used to draw the ticks for the open values (possibly
204     *         {@code null}).
205     *
206     * @see #setOpenTickPaint(Paint)
207     */
208    public Paint getOpenTickPaint() {
209        return this.openTickPaint;
210    }
211
212    /**
213     * Sets the paint used to draw the ticks for the open values and sends a
214     * {@link RendererChangeEvent} to all registered listeners.  If you set
215     * this to {@code null} (the default), the series paint is used
216     * instead.
217     *
218     * @param paint  the paint ({@code null} permitted).
219     *
220     * @see #getOpenTickPaint()
221     */
222    public void setOpenTickPaint(Paint paint) {
223        this.openTickPaint = paint;
224        fireChangeEvent();
225    }
226
227    /**
228     * Returns the paint used to draw the ticks for the close values.
229     *
230     * @return The paint used to draw the ticks for the close values (possibly
231     *         {@code null}).
232     *
233     * @see #setCloseTickPaint(Paint)
234     */
235    public Paint getCloseTickPaint() {
236        return this.closeTickPaint;
237    }
238
239    /**
240     * Sets the paint used to draw the ticks for the close values and sends a
241     * {@link RendererChangeEvent} to all registered listeners.  If you set
242     * this to {@code null} (the default), the series paint is used
243     * instead.
244     *
245     * @param paint  the paint ({@code null} permitted).
246     *
247     * @see #getCloseTickPaint()
248     */
249    public void setCloseTickPaint(Paint paint) {
250        this.closeTickPaint = paint;
251        fireChangeEvent();
252    }
253
254    /**
255     * Returns the tick length (in Java2D units).
256     *
257     * @return The tick length.
258     *
259     * @since 1.0.10
260     *
261     * @see #setTickLength(double)
262     */
263    public double getTickLength() {
264        return this.tickLength;
265    }
266
267    /**
268     * Sets the tick length (in Java2D units) and sends a
269     * {@link RendererChangeEvent} to all registered listeners.
270     *
271     * @param length  the length.
272     *
273     * @since 1.0.10
274     *
275     * @see #getTickLength()
276     */
277    public void setTickLength(double length) {
278        this.tickLength = length;
279        fireChangeEvent();
280    }
281
282    /**
283     * Returns the range of values the renderer requires to display all the
284     * items from the specified dataset.
285     *
286     * @param dataset  the dataset ({@code null} permitted).
287     *
288     * @return The range ({@code null} if the dataset is {@code null}
289     *         or empty).
290     */
291    @Override
292    public Range findRangeBounds(XYDataset dataset) {
293        if (dataset != null) {
294            return DatasetUtils.findRangeBounds(dataset, true);
295        }
296        else {
297            return null;
298        }
299    }
300
301    /**
302     * Draws the visual representation of a single data item.
303     *
304     * @param g2  the graphics device.
305     * @param state  the renderer state.
306     * @param dataArea  the area within which the plot is being drawn.
307     * @param info  collects information about the drawing.
308     * @param plot  the plot (can be used to obtain standard color
309     *              information etc).
310     * @param domainAxis  the domain axis.
311     * @param rangeAxis  the range axis.
312     * @param dataset  the dataset.
313     * @param series  the series index (zero-based).
314     * @param item  the item index (zero-based).
315     * @param crosshairState  crosshair information for the plot
316     *                        ({@code null} permitted).
317     * @param pass  the pass index.
318     */
319    @Override
320    public void drawItem(Graphics2D g2, XYItemRendererState state,
321            Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
322            ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
323            int series, int item, CrosshairState crosshairState, int pass) {
324
325        double x = dataset.getXValue(series, item);
326        if (!domainAxis.getRange().contains(x)) {
327            return;    // the x value is not within the axis range
328        }
329        double xx = domainAxis.valueToJava2D(x, dataArea,
330                plot.getDomainAxisEdge());
331
332        // setup for collecting optional entity info...
333        Shape entityArea = null;
334        EntityCollection entities = null;
335        if (info != null) {
336            entities = info.getOwner().getEntityCollection();
337        }
338
339        PlotOrientation orientation = plot.getOrientation();
340        RectangleEdge location = plot.getRangeAxisEdge();
341
342        Paint itemPaint = getItemPaint(series, item);
343        Stroke itemStroke = getItemStroke(series, item);
344        g2.setPaint(itemPaint);
345        g2.setStroke(itemStroke);
346
347        if (dataset instanceof OHLCDataset) {
348            OHLCDataset hld = (OHLCDataset) dataset;
349
350            double yHigh = hld.getHighValue(series, item);
351            double yLow = hld.getLowValue(series, item);
352            if (!Double.isNaN(yHigh) && !Double.isNaN(yLow)) {
353                double yyHigh = rangeAxis.valueToJava2D(yHigh, dataArea,
354                        location);
355                double yyLow = rangeAxis.valueToJava2D(yLow, dataArea,
356                        location);
357                if (orientation == PlotOrientation.HORIZONTAL) {
358                    g2.draw(new Line2D.Double(yyLow, xx, yyHigh, xx));
359                    entityArea = new Rectangle2D.Double(Math.min(yyLow, yyHigh),
360                            xx - 1.0, Math.abs(yyHigh - yyLow), 2.0);
361                }
362                else if (orientation == PlotOrientation.VERTICAL) {
363                    g2.draw(new Line2D.Double(xx, yyLow, xx, yyHigh));
364                    entityArea = new Rectangle2D.Double(xx - 1.0,
365                            Math.min(yyLow, yyHigh), 2.0,
366                            Math.abs(yyHigh - yyLow));
367                }
368            }
369
370            double delta = getTickLength();
371            if (domainAxis.isInverted()) {
372                delta = -delta;
373            }
374            if (getDrawOpenTicks()) {
375                double yOpen = hld.getOpenValue(series, item);
376                if (!Double.isNaN(yOpen)) {
377                    double yyOpen = rangeAxis.valueToJava2D(yOpen, dataArea,
378                            location);
379                    if (this.openTickPaint != null) {
380                        g2.setPaint(this.openTickPaint);
381                    }
382                    else {
383                        g2.setPaint(itemPaint);
384                    }
385                    if (orientation == PlotOrientation.HORIZONTAL) {
386                        g2.draw(new Line2D.Double(yyOpen, xx + delta, yyOpen,
387                                xx));
388                    }
389                    else if (orientation == PlotOrientation.VERTICAL) {
390                        g2.draw(new Line2D.Double(xx - delta, yyOpen, xx,
391                                yyOpen));
392                    }
393                }
394            }
395
396            if (getDrawCloseTicks()) {
397                double yClose = hld.getCloseValue(series, item);
398                if (!Double.isNaN(yClose)) {
399                    double yyClose = rangeAxis.valueToJava2D(
400                        yClose, dataArea, location);
401                    if (this.closeTickPaint != null) {
402                        g2.setPaint(this.closeTickPaint);
403                    }
404                    else {
405                        g2.setPaint(itemPaint);
406                    }
407                    if (orientation == PlotOrientation.HORIZONTAL) {
408                        g2.draw(new Line2D.Double(yyClose, xx, yyClose,
409                                xx - delta));
410                    }
411                    else if (orientation == PlotOrientation.VERTICAL) {
412                        g2.draw(new Line2D.Double(xx, yyClose, xx + delta,
413                                yyClose));
414                    }
415                }
416            }
417
418        }
419        else {
420            // not a HighLowDataset, so just draw a line connecting this point
421            // with the previous point...
422            if (item > 0) {
423                double x0 = dataset.getXValue(series, item - 1);
424                double y0 = dataset.getYValue(series, item - 1);
425                double y = dataset.getYValue(series, item);
426                if (Double.isNaN(x0) || Double.isNaN(y0) || Double.isNaN(y)) {
427                    return;
428                }
429                double xx0 = domainAxis.valueToJava2D(x0, dataArea,
430                        plot.getDomainAxisEdge());
431                double yy0 = rangeAxis.valueToJava2D(y0, dataArea, location);
432                double yy = rangeAxis.valueToJava2D(y, dataArea, location);
433                if (orientation == PlotOrientation.HORIZONTAL) {
434                    g2.draw(new Line2D.Double(yy0, xx0, yy, xx));
435                }
436                else if (orientation == PlotOrientation.VERTICAL) {
437                    g2.draw(new Line2D.Double(xx0, yy0, xx, yy));
438                }
439            }
440        }
441
442        if (entities != null) {
443            addEntity(entities, entityArea, dataset, series, item, 0.0, 0.0);
444        }
445
446    }
447
448    /**
449     * Returns a clone of the renderer.
450     *
451     * @return A clone.
452     *
453     * @throws CloneNotSupportedException  if the renderer cannot be cloned.
454     */
455    @Override
456    public Object clone() throws CloneNotSupportedException {
457        return super.clone();
458    }
459
460    /**
461     * Tests this renderer for equality with an arbitrary object.
462     *
463     * @param obj  the object ({@code null} permitted).
464     *
465     * @return A boolean.
466     */
467    @Override
468    public boolean equals(Object obj) {
469        if (this == obj) {
470            return true;
471        }
472        if (!(obj instanceof HighLowRenderer)) {
473            return false;
474        }
475        HighLowRenderer that = (HighLowRenderer) obj;
476        if (this.drawOpenTicks != that.drawOpenTicks) {
477            return false;
478        }
479        if (this.drawCloseTicks != that.drawCloseTicks) {
480            return false;
481        }
482        if (!PaintUtils.equal(this.openTickPaint, that.openTickPaint)) {
483            return false;
484        }
485        if (!PaintUtils.equal(this.closeTickPaint, that.closeTickPaint)) {
486            return false;
487        }
488        if (this.tickLength != that.tickLength) {
489            return false;
490        }
491        if (!super.equals(obj)) {
492            return false;
493        }
494        return true;
495    }
496
497    /**
498     * Provides serialization support.
499     *
500     * @param stream  the input stream.
501     *
502     * @throws IOException  if there is an I/O error.
503     * @throws ClassNotFoundException  if there is a classpath problem.
504     */
505    private void readObject(ObjectInputStream stream)
506            throws IOException, ClassNotFoundException {
507        stream.defaultReadObject();
508        this.openTickPaint = SerialUtils.readPaint(stream);
509        this.closeTickPaint = SerialUtils.readPaint(stream);
510    }
511
512    /**
513     * Provides serialization support.
514     *
515     * @param stream  the output stream.
516     *
517     * @throws IOException  if there is an I/O error.
518     */
519    private void writeObject(ObjectOutputStream stream) throws IOException {
520        stream.defaultWriteObject();
521        SerialUtils.writePaint(this.openTickPaint, stream);
522        SerialUtils.writePaint(this.closeTickPaint, stream);
523    }
524
525}