001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-present, by David Gilbert 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 * XYPolygonAnnotation.java
029 * ------------------------
030 * (C) Copyright 2005-present, by David Gilbert and Contributors.
031 *
032 * Original Author:  David Gilbert;
033 * Contributor(s):   Peter Kolb (patch 2809117);
034                     Tracy Hiltbrand (equals/hashCode comply with EqualsVerifier);
035 *
036 */
037
038package org.jfree.chart.annotations;
039
040import java.awt.BasicStroke;
041import java.awt.Color;
042import java.awt.Graphics2D;
043import java.awt.Paint;
044import java.awt.Stroke;
045import java.awt.geom.GeneralPath;
046import java.awt.geom.Rectangle2D;
047import java.io.IOException;
048import java.io.ObjectInputStream;
049import java.io.ObjectOutputStream;
050import java.io.Serializable;
051import java.util.Arrays;
052import java.util.Objects;
053
054import org.jfree.chart.HashUtils;
055import org.jfree.chart.axis.ValueAxis;
056import org.jfree.chart.plot.Plot;
057import org.jfree.chart.plot.PlotOrientation;
058import org.jfree.chart.plot.PlotRenderingInfo;
059import org.jfree.chart.plot.XYPlot;
060import org.jfree.chart.ui.RectangleEdge;
061import org.jfree.chart.util.PaintUtils;
062import org.jfree.chart.util.Args;
063import org.jfree.chart.util.PublicCloneable;
064import org.jfree.chart.util.SerialUtils;
065
066/**
067 * A polygon annotation that can be placed on an {@link XYPlot}.  The
068 * polygon coordinates are specified in data space.
069 */
070public class XYPolygonAnnotation extends AbstractXYAnnotation
071        implements Cloneable, PublicCloneable, Serializable {
072
073    /** For serialization. */
074    private static final long serialVersionUID = -6984203651995900036L;
075
076    /** The polygon. */
077    private double[] polygon;
078
079    /** The stroke used to draw the box outline. */
080    private transient Stroke stroke;
081
082    /** The paint used to draw the box outline. */
083    private transient Paint outlinePaint;
084
085    /** The paint used to fill the box. */
086    private transient Paint fillPaint;
087
088    /**
089     * Creates a new annotation (where, by default, the polygon is drawn
090     * with a black outline).  The array of polygon coordinates must contain
091     * an even number of coordinates (each pair is an (x, y) location on the
092     * plot) and the last point is automatically joined back to the first point.
093     *
094     * @param polygon  the coordinates of the polygon's vertices
095     *     ({@code null} not permitted).
096     */
097    public XYPolygonAnnotation(double[] polygon) {
098        this(polygon, new BasicStroke(1.0f), Color.BLACK);
099    }
100
101    /**
102     * Creates a new annotation where the box is drawn as an outline using
103     * the specified {@code stroke} and {@code outlinePaint}.
104     * The array of polygon coordinates must contain an even number of
105     * coordinates (each pair is an (x, y) location on the plot) and the last
106     * point is automatically joined back to the first point.
107     *
108     * @param polygon  the coordinates of the polygon's vertices
109     *     ({@code null} not permitted).
110     * @param stroke  the shape stroke ({@code null} permitted).
111     * @param outlinePaint  the shape color ({@code null} permitted).
112     */
113    public XYPolygonAnnotation(double[] polygon,
114                               Stroke stroke, Paint outlinePaint) {
115        this(polygon, stroke, outlinePaint, null);
116    }
117
118    /**
119     * Creates a new annotation.  The array of polygon coordinates must
120     * contain an even number of coordinates (each pair is an (x, y) location
121     * on the plot) and the last point is automatically joined back to the
122     * first point.
123     *
124     * @param polygon  the coordinates of the polygon's vertices
125     *     ({@code null} not permitted).
126     * @param stroke  the shape stroke ({@code null} permitted).
127     * @param outlinePaint  the shape color ({@code null} permitted).
128     * @param fillPaint  the paint used to fill the shape ({@code null}
129     *                   permitted).
130     */
131    public XYPolygonAnnotation(double[] polygon, Stroke stroke, 
132            Paint outlinePaint, Paint fillPaint) {
133        super();
134        Args.nullNotPermitted(polygon, "polygon");
135        if (polygon.length % 2 != 0) {
136            throw new IllegalArgumentException("The 'polygon' array must "
137                    + "contain an even number of items.");
138        }
139        this.polygon = polygon.clone();
140        this.stroke = stroke;
141        this.outlinePaint = outlinePaint;
142        this.fillPaint = fillPaint;
143    }
144
145    /**
146     * Returns the coordinates of the polygon's vertices.  The returned array
147     * is a copy, so it is safe to modify without altering the annotation's
148     * state.
149     *
150     * @return The coordinates of the polygon's vertices.
151     */
152    public double[] getPolygonCoordinates() {
153        return this.polygon.clone();
154    }
155
156    /**
157     * Returns the fill paint.
158     *
159     * @return The fill paint (possibly {@code null}).
160     */
161    public Paint getFillPaint() {
162        return this.fillPaint;
163    }
164
165    /**
166     * Returns the outline stroke.
167     *
168     * @return The outline stroke (possibly {@code null}).
169     */
170    public Stroke getOutlineStroke() {
171        return this.stroke;
172    }
173
174    /**
175     * Returns the outline paint.
176     *
177     * @return The outline paint (possibly {@code null}).
178     */
179    public Paint getOutlinePaint() {
180        return this.outlinePaint;
181    }
182
183    /**
184     * Draws the annotation.  This method is usually called by the
185     * {@link XYPlot} class, you shouldn't need to call it directly.
186     *
187     * @param g2  the graphics device.
188     * @param plot  the plot.
189     * @param dataArea  the data area.
190     * @param domainAxis  the domain axis.
191     * @param rangeAxis  the range axis.
192     * @param rendererIndex  the renderer index.
193     * @param info  the plot rendering info.
194     */
195    @Override
196    public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea,
197                     ValueAxis domainAxis, ValueAxis rangeAxis,
198                     int rendererIndex, PlotRenderingInfo info) {
199
200        // if we don't have at least 2 (x, y) coordinates, just return
201        if (this.polygon.length < 4) {
202            return;
203        }
204        PlotOrientation orientation = plot.getOrientation();
205        RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(
206                plot.getDomainAxisLocation(), orientation);
207        RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(
208                plot.getRangeAxisLocation(), orientation);
209
210        GeneralPath area = new GeneralPath();
211        double x = domainAxis.valueToJava2D(this.polygon[0], dataArea,
212                domainEdge);
213        double y = rangeAxis.valueToJava2D(this.polygon[1], dataArea,
214                rangeEdge);
215        if (orientation == PlotOrientation.HORIZONTAL) {
216            area.moveTo((float) y, (float) x);
217            for (int i = 2; i < this.polygon.length; i += 2) {
218                x = domainAxis.valueToJava2D(this.polygon[i], dataArea,
219                        domainEdge);
220                y = rangeAxis.valueToJava2D(this.polygon[i + 1], dataArea,
221                        rangeEdge);
222                area.lineTo((float) y, (float) x);
223            }
224            area.closePath();
225        }
226        else if (orientation == PlotOrientation.VERTICAL) {
227            area.moveTo((float) x, (float) y);
228            for (int i = 2; i < this.polygon.length; i += 2) {
229                x = domainAxis.valueToJava2D(this.polygon[i], dataArea,
230                        domainEdge);
231                y = rangeAxis.valueToJava2D(this.polygon[i + 1], dataArea,
232                        rangeEdge);
233                area.lineTo((float) x, (float) y);
234            }
235            area.closePath();
236       }
237
238
239        if (this.fillPaint != null) {
240            g2.setPaint(this.fillPaint);
241            g2.fill(area);
242        }
243
244        if (this.stroke != null && this.outlinePaint != null) {
245            g2.setPaint(this.outlinePaint);
246            g2.setStroke(this.stroke);
247            g2.draw(area);
248        }
249        addEntity(info, area, rendererIndex, getToolTipText(), getURL());
250
251    }
252
253    /**
254     * Tests this annotation for equality with an arbitrary object.
255     *
256     * @param obj  the object ({@code null} permitted).
257     *
258     * @return A boolean.
259     */
260    @Override
261    public boolean equals(Object obj) {
262        if (obj == this) {
263            return true;
264        }
265        if (!(obj instanceof XYPolygonAnnotation)) {
266            return false;
267        }
268        XYPolygonAnnotation that = (XYPolygonAnnotation) obj;
269        if (!Arrays.equals(this.polygon, that.polygon)) {
270            return false;
271        }
272        if (!Objects.equals(this.stroke, that.stroke)) {
273            return false;
274        }
275        if (!PaintUtils.equal(this.outlinePaint, that.outlinePaint)) {
276            return false;
277        }
278        if (!PaintUtils.equal(this.fillPaint, that.fillPaint)) {
279            return false;
280        }
281
282        // fix the "equals not symmetric" problem
283        if (!that.canEqual(this)) {
284            return false;
285        }
286
287        return super.equals(obj);
288    }
289
290    /**
291     * Ensures symmetry between super/subclass implementations of equals. For
292     * more detail, see http://jqno.nl/equalsverifier/manual/inheritance.
293     *
294     * @param other Object
295     * 
296     * @return true ONLY if the parameter is THIS class type
297     */
298    @Override
299    public boolean canEqual(Object other) {
300        // fix the "equals not symmetric" problem
301        return (other instanceof XYPolygonAnnotation);
302    }
303    
304    /**
305     * Returns a hash code for this instance.
306     *
307     * @return A hash code.
308     */
309    @Override
310    public int hashCode() {
311        int hash = super.hashCode(); // equals calls superclass, hashCode must also
312        hash = 13 * hash + HashUtils.hashCodeForPaint(this.fillPaint);
313        hash = 13 * hash + HashUtils.hashCodeForPaint(this.outlinePaint);
314        hash = 13 * hash + Objects.hashCode(this.stroke);
315        hash = 13 * hash + Arrays.hashCode(this.polygon);
316        return hash;
317    }
318
319    /**
320     * Returns a clone.
321     *
322     * @return A clone.
323     *
324     * @throws CloneNotSupportedException not thrown by this class, but may be
325     *                                    by subclasses.
326     */
327    @Override
328    public Object clone() throws CloneNotSupportedException {
329        return super.clone();
330    }
331
332    /**
333     * Provides serialization support.
334     *
335     * @param stream  the output stream ({@code null} not permitted).
336     *
337     * @throws IOException if there is an I/O error.
338     */
339    private void writeObject(ObjectOutputStream stream) throws IOException {
340        stream.defaultWriteObject();
341        SerialUtils.writeStroke(this.stroke, stream);
342        SerialUtils.writePaint(this.outlinePaint, stream);
343        SerialUtils.writePaint(this.fillPaint, stream);
344    }
345
346    /**
347     * Provides serialization support.
348     *
349     * @param stream  the input stream ({@code null} not permitted).
350     *
351     * @throws IOException  if there is an I/O error.
352     * @throws ClassNotFoundException  if there is a classpath problem.
353     */
354    private void readObject(ObjectInputStream stream)
355            throws IOException, ClassNotFoundException {
356        stream.defaultReadObject();
357        this.stroke = SerialUtils.readStroke(stream);
358        this.outlinePaint = SerialUtils.readPaint(stream);
359        this.fillPaint = SerialUtils.readPaint(stream);
360    }
361
362}