001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2013, 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 * ChartEntity.java
029 * ----------------
030 * (C) Copyright 2002-2008, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Richard Atkinson;
034 *                   Xavier Poinsard;
035 *                   Robert Fuller;
036 *
037 * Changes:
038 * --------
039 * 23-May-2002 : Version 1 (DG);
040 * 12-Jun-2002 : Added Javadoc comments (DG);
041 * 26-Jun-2002 : Added methods for image maps (DG);
042 * 05-Aug-2002 : Added constructor and accessors for URL support in image maps
043 *               Added getImageMapAreaTag() - previously in subclasses (RA);
044 * 05-Sep-2002 : Added getImageMapAreaTag(boolean) to support OverLIB for
045 *               tooltips http://www.bosrup.com/web/overlib (RA);
046 * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG);
047 * 08-Oct-2002 : Changed getImageMapAreaTag to use title instead of alt
048 *               attribute so HTML image maps now work in Mozilla and Opera as
049 *               well as Internet Explorer (RA);
050 * 13-Mar-2003 : Change getImageMapAreaTag to only return a tag when there is a
051 *               tooltip or URL, as suggested by Xavier Poinsard (see Feature
052 *               Request 688079) (DG);
053 * 12-Aug-2003 : Added support for custom image maps using
054 *               ToolTipTagFragmentGenerator and URLTagFragmentGenerator (RA);
055 * 02-Sep-2003 : Incorporated fix (791901) submitted by Robert Fuller (DG);
056 * 19-May-2004 : Added equals() method and implemented Cloneable and
057 *               Serializable (DG);
058 * 29-Sep-2004 : Implemented PublicCloneable (DG);
059 * 13-Jan-2005 : Fixed for compliance with XHTML 1.0 (DG);
060 * 18-Apr-2005 : Use StringBuffer (DG);
061 * 20-Apr-2005 : Added toString() implementation (DG);
062 * ------------- JFREECHART 1.0.x ---------------------------------------------
063 * 06-Feb-2007 : API doc update (DG);
064 * 13-Nov-2007 : Reorganised equals(), implemented hashCode (DG);
065 * 04-Dec-2007 : Added 'nohref' attribute in getImageMapAreaTag() method, to
066 *               fix bug 1460195 (DG);
067 * 04-Dec-2007 : Escape the toolTipText and urlText in getImageMapAreaTag() to
068 *               prevent special characters corrupting the HTML (DG);
069 * 05-Dec-2007 : Previous change reverted - let the tool tip and url tag
070 *               generators handle filtering / escaping (DG);
071 *
072 */
073
074package org.jfree.chart.entity;
075
076import java.awt.Shape;
077import java.awt.geom.PathIterator;
078import java.awt.geom.Rectangle2D;
079import java.io.IOException;
080import java.io.ObjectInputStream;
081import java.io.ObjectOutputStream;
082import java.io.Serializable;
083
084import org.jfree.chart.HashUtilities;
085import org.jfree.chart.imagemap.ToolTipTagFragmentGenerator;
086import org.jfree.chart.imagemap.URLTagFragmentGenerator;
087import org.jfree.chart.util.ParamChecks;
088import org.jfree.io.SerialUtilities;
089import org.jfree.util.ObjectUtilities;
090import org.jfree.util.PublicCloneable;
091
092/**
093 * A class that captures information about some component of a chart (a bar,
094 * line etc).
095 */
096public class ChartEntity implements Cloneable, PublicCloneable, Serializable {
097
098    /** For serialization. */
099    private static final long serialVersionUID = -4445994133561919083L;
100
101    /** The area occupied by the entity (in Java 2D space). */
102    private transient Shape area;
103
104    /** The tool tip text for the entity. */
105    private String toolTipText;
106
107    /** The URL text for the entity. */
108    private String urlText;
109
110    /**
111     * Creates a new chart entity.
112     *
113     * @param area  the area (<code>null</code> not permitted).
114     */
115    public ChartEntity(Shape area) {
116        // defer argument checks...
117        this(area, null);
118    }
119
120    /**
121     * Creates a new chart entity.
122     *
123     * @param area  the area (<code>null</code> not permitted).
124     * @param toolTipText  the tool tip text (<code>null</code> permitted).
125     */
126    public ChartEntity(Shape area, String toolTipText) {
127        // defer argument checks...
128        this(area, toolTipText, null);
129    }
130
131    /**
132     * Creates a new entity.
133     *
134     * @param area  the area (<code>null</code> not permitted).
135     * @param toolTipText  the tool tip text (<code>null</code> permitted).
136     * @param urlText  the URL text for HTML image maps (<code>null</code>
137     *                 permitted).
138     */
139    public ChartEntity(Shape area, String toolTipText, String urlText) {
140        ParamChecks.nullNotPermitted(area, "area");
141        this.area = area;
142        this.toolTipText = toolTipText;
143        this.urlText = urlText;
144    }
145
146    /**
147     * Returns the area occupied by the entity (in Java 2D space).
148     *
149     * @return The area (never <code>null</code>).
150     */
151    public Shape getArea() {
152        return this.area;
153    }
154
155    /**
156     * Sets the area for the entity.
157     * <P>
158     * This class conveys information about chart entities back to a client.
159     * Setting this area doesn't change the entity (which has already been
160     * drawn).
161     *
162     * @param area  the area (<code>null</code> not permitted).
163     */
164    public void setArea(Shape area) {
165        ParamChecks.nullNotPermitted(area, "area");
166        this.area = area;
167    }
168
169    /**
170     * Returns the tool tip text for the entity.  Be aware that this text
171     * may have been generated from user supplied data, so for security
172     * reasons some form of filtering should be applied before incorporating
173     * this text into any HTML output.
174     *
175     * @return The tool tip text (possibly <code>null</code>).
176     */
177    public String getToolTipText() {
178        return this.toolTipText;
179    }
180
181    /**
182     * Sets the tool tip text.
183     *
184     * @param text  the text (<code>null</code> permitted).
185     */
186    public void setToolTipText(String text) {
187        this.toolTipText = text;
188    }
189
190    /**
191     * Returns the URL text for the entity.  Be aware that this text
192     * may have been generated from user supplied data, so some form of
193     * filtering should be applied before this "URL" is used in any output.
194     *
195     * @return The URL text (possibly <code>null</code>).
196     */
197    public String getURLText() {
198        return this.urlText;
199    }
200
201    /**
202     * Sets the URL text.
203     *
204     * @param text the text (<code>null</code> permitted).
205     */
206    public void setURLText(String text) {
207        this.urlText = text;
208    }
209
210    /**
211     * Returns a string describing the entity area.  This string is intended
212     * for use in an AREA tag when generating an image map.
213     *
214     * @return The shape type (never <code>null</code>).
215     */
216    public String getShapeType() {
217        if (this.area instanceof Rectangle2D) {
218            return "rect";
219        }
220        else {
221            return "poly";
222        }
223    }
224
225    /**
226     * Returns the shape coordinates as a string.
227     *
228     * @return The shape coordinates (never <code>null</code>).
229     */
230    public String getShapeCoords() {
231        if (this.area instanceof Rectangle2D) {
232            return getRectCoords((Rectangle2D) this.area);
233        }
234        else {
235            return getPolyCoords(this.area);
236        }
237    }
238
239    /**
240     * Returns a string containing the coordinates (x1, y1, x2, y2) for a given
241     * rectangle.  This string is intended for use in an image map.
242     *
243     * @param rectangle  the rectangle (<code>null</code> not permitted).
244     *
245     * @return Upper left and lower right corner of a rectangle.
246     */
247    private String getRectCoords(Rectangle2D rectangle) {
248        ParamChecks.nullNotPermitted(rectangle, "rectangle");
249        int x1 = (int) rectangle.getX();
250        int y1 = (int) rectangle.getY();
251        int x2 = x1 + (int) rectangle.getWidth();
252        int y2 = y1 + (int) rectangle.getHeight();
253        //      fix by rfuller
254        if (x2 == x1) {
255            x2++;
256        }
257        if (y2 == y1) {
258            y2++;
259        }
260        //      end fix by rfuller
261        return x1 + "," + y1 + "," + x2 + "," + y2;
262    }
263
264    /**
265     * Returns a string containing the coordinates for a given shape.  This
266     * string is intended for use in an image map.
267     *
268     * @param shape  the shape (<code>null</code> not permitted).
269     *
270     * @return The coordinates for a given shape as string.
271     */
272    private String getPolyCoords(Shape shape) {
273        ParamChecks.nullNotPermitted(shape, "shape");
274        StringBuilder result = new StringBuilder();
275        boolean first = true;
276        float[] coords = new float[6];
277        PathIterator pi = shape.getPathIterator(null, 1.0);
278        while (!pi.isDone()) {
279            pi.currentSegment(coords);
280            if (first) {
281                first = false;
282                result.append((int) coords[0]);
283                result.append(",").append((int) coords[1]);
284            }
285            else {
286                result.append(",");
287                result.append((int) coords[0]);
288                result.append(",");
289                result.append((int) coords[1]);
290            }
291            pi.next();
292        }
293        return result.toString();
294    }
295
296    /**
297     * Returns an HTML image map tag for this entity.  The returned fragment
298     * should be <code>XHTML 1.0</code> compliant.
299     *
300     * @param toolTipTagFragmentGenerator  a generator for the HTML fragment
301     *     that will contain the tooltip text (<code>null</code> not permitted
302     *     if this entity contains tooltip information).
303     * @param urlTagFragmentGenerator  a generator for the HTML fragment that
304     *     will contain the URL reference (<code>null</code> not permitted if
305     *     this entity has a URL).
306     *
307     * @return The HTML tag.
308     */
309    public String getImageMapAreaTag(
310            ToolTipTagFragmentGenerator toolTipTagFragmentGenerator,
311            URLTagFragmentGenerator urlTagFragmentGenerator) {
312
313        StringBuilder tag = new StringBuilder();
314        boolean hasURL = (this.urlText == null ? false
315                : !this.urlText.equals(""));
316        boolean hasToolTip = (this.toolTipText == null ? false
317                : !this.toolTipText.equals(""));
318        if (hasURL || hasToolTip) {
319            tag.append("<area shape=\"").append(getShapeType()).append("\"")
320                    .append(" coords=\"").append(getShapeCoords()).append("\"");
321            if (hasToolTip) {
322                tag.append(toolTipTagFragmentGenerator.generateToolTipFragment(
323                        this.toolTipText));
324            }
325            if (hasURL) {
326                tag.append(urlTagFragmentGenerator.generateURLFragment(
327                        this.urlText));
328            }
329            else {
330                tag.append(" nohref=\"nohref\"");
331            }
332            // if there is a tool tip, we expect it to generate the title and
333            // alt values, so we only add an empty alt if there is no tooltip
334            if (!hasToolTip) {
335                tag.append(" alt=\"\"");
336            }
337            tag.append("/>");
338        }
339        return tag.toString();
340    }
341
342    /**
343     * Returns a string representation of the chart entity, useful for
344     * debugging.
345     *
346     * @return A string.
347     */
348    @Override
349    public String toString() {
350        StringBuilder sb = new StringBuilder("ChartEntity: ");
351        sb.append("tooltip = ");
352        sb.append(this.toolTipText);
353        return sb.toString();
354    }
355
356    /**
357     * Tests the entity for equality with an arbitrary object.
358     *
359     * @param obj  the object to test against (<code>null</code> permitted).
360     *
361     * @return A boolean.
362     */
363    @Override
364    public boolean equals(Object obj) {
365        if (obj == this) {
366            return true;
367        }
368        if (!(obj instanceof ChartEntity)) {
369            return false;
370        }
371        ChartEntity that = (ChartEntity) obj;
372        if (!this.area.equals(that.area)) {
373            return false;
374        }
375        if (!ObjectUtilities.equal(this.toolTipText, that.toolTipText)) {
376            return false;
377        }
378        if (!ObjectUtilities.equal(this.urlText, that.urlText)) {
379            return false;
380        }
381        return true;
382    }
383
384    /**
385     * Returns a hash code for this instance.
386     *
387     * @return A hash code.
388     */
389    @Override
390    public int hashCode() {
391        int result = 37;
392        result = HashUtilities.hashCode(result, this.toolTipText);
393        result = HashUtilities.hashCode(result, this.urlText);
394        return result;
395    }
396
397    /**
398     * Returns a clone of the entity.
399     *
400     * @return A clone.
401     *
402     * @throws CloneNotSupportedException if there is a problem cloning the
403     *         entity.
404     */
405    @Override
406    public Object clone() throws CloneNotSupportedException {
407        return super.clone();
408    }
409
410    /**
411     * Provides serialization support.
412     *
413     * @param stream  the output stream.
414     *
415     * @throws IOException  if there is an I/O error.
416     */
417    private void writeObject(ObjectOutputStream stream) throws IOException {
418        stream.defaultWriteObject();
419        SerialUtilities.writeShape(this.area, stream);
420     }
421
422    /**
423     * Provides serialization support.
424     *
425     * @param stream  the input stream.
426     *
427     * @throws IOException  if there is an I/O error.
428     * @throws ClassNotFoundException  if there is a classpath problem.
429     */
430    private void readObject(ObjectInputStream stream)
431        throws IOException, ClassNotFoundException {
432        stream.defaultReadObject();
433        this.area = SerialUtilities.readShape(stream);
434    }
435
436}