001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2021, 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 * XYPointerAnnotation.java
029 * ------------------------
030 * (C) Copyright 2003-2021, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Peter Kolb (patch 2809117);
034 *
035 */
036
037package org.jfree.chart.annotations;
038
039import java.awt.BasicStroke;
040import java.awt.Color;
041import java.awt.Graphics2D;
042import java.awt.Paint;
043import java.awt.Shape;
044import java.awt.Stroke;
045import java.awt.geom.GeneralPath;
046import java.awt.geom.Line2D;
047import java.awt.geom.Rectangle2D;
048import java.io.IOException;
049import java.io.ObjectInputStream;
050import java.io.ObjectOutputStream;
051import java.io.Serializable;
052import java.util.Objects;
053
054import org.jfree.chart.HashUtils;
055import org.jfree.chart.axis.ValueAxis;
056import org.jfree.chart.event.AnnotationChangeEvent;
057import org.jfree.chart.plot.Plot;
058import org.jfree.chart.plot.PlotOrientation;
059import org.jfree.chart.plot.PlotRenderingInfo;
060import org.jfree.chart.plot.XYPlot;
061import org.jfree.chart.text.TextUtils;
062import org.jfree.chart.ui.RectangleEdge;
063import org.jfree.chart.util.Args;
064import org.jfree.chart.util.PublicCloneable;
065import org.jfree.chart.util.SerialUtils;
066
067/**
068 * An arrow and label that can be placed on an {@link XYPlot}.  The arrow is
069 * drawn at a user-definable angle so that it points towards the (x, y)
070 * location for the annotation.
071 * <p>
072 * The arrow length (and its offset from the (x, y) location) is controlled by
073 * the tip radius and the base radius attributes.  Imagine two circles around
074 * the (x, y) coordinate: the inner circle defined by the tip radius, and the
075 * outer circle defined by the base radius.  Now, draw the arrow starting at
076 * some point on the outer circle (the point is determined by the angle), with
077 * the arrow tip being drawn at a corresponding point on the inner circle.
078 */
079public class XYPointerAnnotation extends XYTextAnnotation
080        implements Cloneable, PublicCloneable, Serializable {
081
082    /** For serialization. */
083    private static final long serialVersionUID = -4031161445009858551L;
084
085    /** The default tip radius (in Java2D units). */
086    public static final double DEFAULT_TIP_RADIUS = 10.0;
087
088    /** The default base radius (in Java2D units). */
089    public static final double DEFAULT_BASE_RADIUS = 30.0;
090
091    /** The default label offset (in Java2D units). */
092    public static final double DEFAULT_LABEL_OFFSET = 3.0;
093
094    /** The default arrow length (in Java2D units). */
095    public static final double DEFAULT_ARROW_LENGTH = 5.0;
096
097    /** The default arrow width (in Java2D units). */
098    public static final double DEFAULT_ARROW_WIDTH = 3.0;
099
100    /** The angle of the arrow's line (in radians). */
101    private double angle;
102
103    /**
104     * The radius from the (x, y) point to the tip of the arrow (in Java2D
105     * units).
106     */
107    private double tipRadius;
108
109    /**
110     * The radius from the (x, y) point to the start of the arrow line (in
111     * Java2D units).
112     */
113    private double baseRadius;
114
115    /** The length of the arrow head (in Java2D units). */
116    private double arrowLength;
117
118    /** The arrow width (in Java2D units, per side). */
119    private double arrowWidth;
120
121    /** The arrow stroke. */
122    private transient Stroke arrowStroke;
123
124    /** The arrow paint. */
125    private transient Paint arrowPaint;
126
127    /** The radius from the base point to the anchor point for the label. */
128    private double labelOffset;
129
130    /**
131     * Creates a new label and arrow annotation.
132     *
133     * @param label  the label ({@code null} permitted).
134     * @param x  the x-coordinate (measured against the chart's domain axis).
135     * @param y  the y-coordinate (measured against the chart's range axis).
136     * @param angle  the angle of the arrow's line (in radians).
137     */
138    public XYPointerAnnotation(String label, double x, double y, double angle) {
139
140        super(label, x, y);
141        this.angle = angle;
142        this.tipRadius = DEFAULT_TIP_RADIUS;
143        this.baseRadius = DEFAULT_BASE_RADIUS;
144        this.arrowLength = DEFAULT_ARROW_LENGTH;
145        this.arrowWidth = DEFAULT_ARROW_WIDTH;
146        this.labelOffset = DEFAULT_LABEL_OFFSET;
147        this.arrowStroke = new BasicStroke(1.0f);
148        this.arrowPaint = Color.BLACK;
149
150    }
151
152    /**
153     * Returns the angle of the arrow.
154     *
155     * @return The angle (in radians).
156     *
157     * @see #setAngle(double)
158     */
159    public double getAngle() {
160        return this.angle;
161    }
162
163    /**
164     * Sets the angle of the arrow and sends an
165     * {@link AnnotationChangeEvent} to all registered listeners.
166     *
167     * @param angle  the angle (in radians).
168     *
169     * @see #getAngle()
170     */
171    public void setAngle(double angle) {
172        this.angle = angle;
173        fireAnnotationChanged();
174    }
175
176    /**
177     * Returns the tip radius.
178     *
179     * @return The tip radius (in Java2D units).
180     *
181     * @see #setTipRadius(double)
182     */
183    public double getTipRadius() {
184        return this.tipRadius;
185    }
186
187    /**
188     * Sets the tip radius and sends an
189     * {@link AnnotationChangeEvent} to all registered listeners.
190     *
191     * @param radius  the radius (in Java2D units).
192     *
193     * @see #getTipRadius()
194     */
195    public void setTipRadius(double radius) {
196        this.tipRadius = radius;
197        fireAnnotationChanged();
198    }
199
200    /**
201     * Returns the base radius.
202     *
203     * @return The base radius (in Java2D units).
204     *
205     * @see #setBaseRadius(double)
206     */
207    public double getBaseRadius() {
208        return this.baseRadius;
209    }
210
211    /**
212     * Sets the base radius and sends an
213     * {@link AnnotationChangeEvent} to all registered listeners.
214     *
215     * @param radius  the radius (in Java2D units).
216     *
217     * @see #getBaseRadius()
218     */
219    public void setBaseRadius(double radius) {
220        this.baseRadius = radius;
221        fireAnnotationChanged();
222    }
223
224    /**
225     * Returns the label offset.
226     *
227     * @return The label offset (in Java2D units).
228     *
229     * @see #setLabelOffset(double)
230     */
231    public double getLabelOffset() {
232        return this.labelOffset;
233    }
234
235    /**
236     * Sets the label offset (from the arrow base, continuing in a straight
237     * line, in Java2D units) and sends an
238     * {@link AnnotationChangeEvent} to all registered listeners.
239     *
240     * @param offset  the offset (in Java2D units).
241     *
242     * @see #getLabelOffset()
243     */
244    public void setLabelOffset(double offset) {
245        this.labelOffset = offset;
246        fireAnnotationChanged();
247    }
248
249    /**
250     * Returns the arrow length.
251     *
252     * @return The arrow length.
253     *
254     * @see #setArrowLength(double)
255     */
256    public double getArrowLength() {
257        return this.arrowLength;
258    }
259
260    /**
261     * Sets the arrow length and sends an
262     * {@link AnnotationChangeEvent} to all registered listeners.
263     *
264     * @param length  the length.
265     *
266     * @see #getArrowLength()
267     */
268    public void setArrowLength(double length) {
269        this.arrowLength = length;
270        fireAnnotationChanged();
271    }
272
273    /**
274     * Returns the arrow width.
275     *
276     * @return The arrow width (in Java2D units).
277     *
278     * @see #setArrowWidth(double)
279     */
280    public double getArrowWidth() {
281        return this.arrowWidth;
282    }
283
284    /**
285     * Sets the arrow width and sends an
286     * {@link AnnotationChangeEvent} to all registered listeners.
287     *
288     * @param width  the width (in Java2D units).
289     *
290     * @see #getArrowWidth()
291     */
292    public void setArrowWidth(double width) {
293        this.arrowWidth = width;
294        fireAnnotationChanged();
295    }
296
297    /**
298     * Returns the stroke used to draw the arrow line.
299     *
300     * @return The arrow stroke (never {@code null}).
301     *
302     * @see #setArrowStroke(Stroke)
303     */
304    public Stroke getArrowStroke() {
305        return this.arrowStroke;
306    }
307
308    /**
309     * Sets the stroke used to draw the arrow line and sends an
310     * {@link AnnotationChangeEvent} to all registered listeners.
311     *
312     * @param stroke  the stroke ({@code null} not permitted).
313     *
314     * @see #getArrowStroke()
315     */
316    public void setArrowStroke(Stroke stroke) {
317        Args.nullNotPermitted(stroke, "stroke");
318        this.arrowStroke = stroke;
319        fireAnnotationChanged();
320    }
321
322    /**
323     * Returns the paint used for the arrow.
324     *
325     * @return The arrow paint (never {@code null}).
326     *
327     * @see #setArrowPaint(Paint)
328     */
329    public Paint getArrowPaint() {
330        return this.arrowPaint;
331    }
332
333    /**
334     * Sets the paint used for the arrow and sends an
335     * {@link AnnotationChangeEvent} to all registered listeners.
336     *
337     * @param paint  the arrow paint ({@code null} not permitted).
338     *
339     * @see #getArrowPaint()
340     */
341    public void setArrowPaint(Paint paint) {
342        Args.nullNotPermitted(paint, "paint");
343        this.arrowPaint = paint;
344        fireAnnotationChanged();
345    }
346
347    /**
348     * Draws the annotation.
349     *
350     * @param g2  the graphics device.
351     * @param plot  the plot.
352     * @param dataArea  the data area.
353     * @param domainAxis  the domain axis.
354     * @param rangeAxis  the range axis.
355     * @param rendererIndex  the renderer index.
356     * @param info  the plot rendering info.
357     */
358    @Override
359    public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea,
360            ValueAxis domainAxis, ValueAxis rangeAxis, int rendererIndex, 
361            PlotRenderingInfo info) {
362
363        PlotOrientation orientation = plot.getOrientation();
364        RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(
365                plot.getDomainAxisLocation(), orientation);
366        RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(
367                plot.getRangeAxisLocation(), orientation);
368        double j2DX = domainAxis.valueToJava2D(getX(), dataArea, domainEdge);
369        double j2DY = rangeAxis.valueToJava2D(getY(), dataArea, rangeEdge);
370        if (orientation == PlotOrientation.HORIZONTAL) {
371            double temp = j2DX;
372            j2DX = j2DY;
373            j2DY = temp;
374        }
375        double startX = j2DX + Math.cos(this.angle) * this.baseRadius;
376        double startY = j2DY + Math.sin(this.angle) * this.baseRadius;
377
378        double endX = j2DX + Math.cos(this.angle) * this.tipRadius;
379        double endY = j2DY + Math.sin(this.angle) * this.tipRadius;
380
381        double arrowBaseX = endX + Math.cos(this.angle) * this.arrowLength;
382        double arrowBaseY = endY + Math.sin(this.angle) * this.arrowLength;
383
384        double arrowLeftX = arrowBaseX
385                + Math.cos(this.angle + Math.PI / 2.0) * this.arrowWidth;
386        double arrowLeftY = arrowBaseY
387                + Math.sin(this.angle + Math.PI / 2.0) * this.arrowWidth;
388
389        double arrowRightX = arrowBaseX
390                - Math.cos(this.angle + Math.PI / 2.0) * this.arrowWidth;
391        double arrowRightY = arrowBaseY
392                - Math.sin(this.angle + Math.PI / 2.0) * this.arrowWidth;
393
394        GeneralPath arrow = new GeneralPath();
395        arrow.moveTo((float) endX, (float) endY);
396        arrow.lineTo((float) arrowLeftX, (float) arrowLeftY);
397        arrow.lineTo((float) arrowRightX, (float) arrowRightY);
398        arrow.closePath();
399
400        g2.setStroke(this.arrowStroke);
401        g2.setPaint(this.arrowPaint);
402        Line2D line = new Line2D.Double(startX, startY, arrowBaseX, arrowBaseY);
403        g2.draw(line);
404        g2.fill(arrow);
405
406        // draw the label
407        double labelX = j2DX + Math.cos(this.angle) * (this.baseRadius
408                + this.labelOffset);
409        double labelY = j2DY + Math.sin(this.angle) * (this.baseRadius
410                + this.labelOffset);
411        g2.setFont(getFont());
412        Shape hotspot = TextUtils.calculateRotatedStringBounds(
413                getText(), g2, (float) labelX, (float) labelY, getTextAnchor(),
414                getRotationAngle(), getRotationAnchor());
415        if (getBackgroundPaint() != null) {
416            g2.setPaint(getBackgroundPaint());
417            g2.fill(hotspot);
418        }
419        g2.setPaint(getPaint());
420        TextUtils.drawRotatedString(getText(), g2, (float) labelX,
421                (float) labelY, getTextAnchor(), getRotationAngle(),
422                getRotationAnchor());
423        if (isOutlineVisible()) {
424            g2.setStroke(getOutlineStroke());
425            g2.setPaint(getOutlinePaint());
426            g2.draw(hotspot);
427        }
428
429        String toolTip = getToolTipText();
430        String url = getURL();
431        if (toolTip != null || url != null) {
432            addEntity(info, hotspot, rendererIndex, toolTip, url);
433        }
434
435    }
436
437    /**
438     * Tests this annotation for equality with an arbitrary object.
439     *
440     * @param obj  the object ({@code null} permitted).
441     *
442     * @return {@code true} or {@code false}.
443     */
444    @Override
445    public boolean equals(Object obj) {
446        if (obj == this) {
447            return true;
448        }
449        if (!(obj instanceof XYPointerAnnotation)) {
450            return false;
451        }
452        XYPointerAnnotation that = (XYPointerAnnotation) obj;
453        if (this.angle != that.angle) {
454            return false;
455        }
456        if (this.tipRadius != that.tipRadius) {
457            return false;
458        }
459        if (this.baseRadius != that.baseRadius) {
460            return false;
461        }
462        if (this.arrowLength != that.arrowLength) {
463            return false;
464        }
465        if (this.arrowWidth != that.arrowWidth) {
466            return false;
467        }
468        if (!this.arrowPaint.equals(that.arrowPaint)) {
469            return false;
470        }
471        if (!Objects.equals(this.arrowStroke, that.arrowStroke)) {
472            return false;
473        }
474        if (this.labelOffset != that.labelOffset) {
475            return false;
476        }
477        return super.equals(obj);
478    }
479
480    /**
481     * Returns a hash code for this instance.
482     *
483     * @return A hash code.
484     */
485    @Override
486    public int hashCode() {
487        int result = super.hashCode();
488        long temp = Double.doubleToLongBits(this.angle);
489        result = 37 * result + (int) (temp ^ (temp >>> 32));
490        temp = Double.doubleToLongBits(this.tipRadius);
491        result = 37 * result + (int) (temp ^ (temp >>> 32));
492        temp = Double.doubleToLongBits(this.baseRadius);
493        result = 37 * result + (int) (temp ^ (temp >>> 32));
494        temp = Double.doubleToLongBits(this.arrowLength);
495        result = 37 * result + (int) (temp ^ (temp >>> 32));
496        temp = Double.doubleToLongBits(this.arrowWidth);
497        result = 37 * result + (int) (temp ^ (temp >>> 32));
498        result = result * 37 + HashUtils.hashCodeForPaint(this.arrowPaint);
499        result = result * 37 + this.arrowStroke.hashCode();
500        temp = Double.doubleToLongBits(this.labelOffset);
501        result = 37 * result + (int) (temp ^ (temp >>> 32));
502        return result;
503    }
504
505    /**
506     * Returns a clone of the annotation.
507     *
508     * @return A clone.
509     *
510     * @throws CloneNotSupportedException  if the annotation can't be cloned.
511     */
512    @Override
513    public Object clone() throws CloneNotSupportedException {
514        return super.clone();
515    }
516
517    /**
518     * Provides serialization support.
519     *
520     * @param stream  the output stream.
521     *
522     * @throws IOException if there is an I/O error.
523     */
524    private void writeObject(ObjectOutputStream stream) throws IOException {
525        stream.defaultWriteObject();
526        SerialUtils.writePaint(this.arrowPaint, stream);
527        SerialUtils.writeStroke(this.arrowStroke, stream);
528    }
529
530    /**
531     * Provides serialization support.
532     *
533     * @param stream  the input stream.
534     *
535     * @throws IOException  if there is an I/O error.
536     * @throws ClassNotFoundException  if there is a classpath problem.
537     */
538    private void readObject(ObjectInputStream stream)
539        throws IOException, ClassNotFoundException {
540        stream.defaultReadObject();
541        this.arrowPaint = SerialUtils.readPaint(stream);
542        this.arrowStroke = SerialUtils.readStroke(stream);
543    }
544
545}