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 * CrosshairOverlay.java
029 * ---------------------
030 * (C) Copyright 2011-2017, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   John Matthews;
034 *
035 * Changes:
036 * --------
037 * 09-Apr-2009 : Version 1 (DG);
038 * 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
039 * 02-Jul-2013 : Use ParamChecks (DG);
040 * 05-Mar-2016 : Fix label outline stroke (DG);
041 *
042 */
043
044package org.jfree.chart.panel;
045
046import java.awt.Font;
047import java.awt.Graphics2D;
048import java.awt.Paint;
049import java.awt.Rectangle;
050import java.awt.Shape;
051import java.awt.Stroke;
052import java.awt.geom.Line2D;
053import java.awt.geom.Point2D;
054import java.awt.geom.Rectangle2D;
055import java.beans.PropertyChangeEvent;
056import java.beans.PropertyChangeListener;
057import java.io.Serializable;
058import java.util.ArrayList;
059import java.util.Iterator;
060import java.util.List;
061import org.jfree.chart.ChartPanel;
062import org.jfree.chart.JFreeChart;
063import org.jfree.chart.axis.ValueAxis;
064import org.jfree.chart.event.OverlayChangeEvent;
065import org.jfree.chart.plot.Crosshair;
066import org.jfree.chart.plot.PlotOrientation;
067import org.jfree.chart.plot.XYPlot;
068import org.jfree.chart.text.TextUtils;
069import org.jfree.chart.ui.RectangleAnchor;
070import org.jfree.chart.ui.RectangleEdge;
071import org.jfree.chart.ui.TextAnchor;
072import org.jfree.chart.util.ObjectUtils;
073import org.jfree.chart.util.Args;
074import org.jfree.chart.util.PublicCloneable;
075
076/**
077 * An overlay for a {@link ChartPanel} that draws crosshairs on a plot.
078 *
079 * @since 1.0.13
080 */
081public class CrosshairOverlay extends AbstractOverlay implements Overlay,
082        PropertyChangeListener, PublicCloneable, Cloneable, Serializable {
083
084    /** Storage for the crosshairs along the x-axis. */
085    private List<Crosshair> xCrosshairs;
086
087    /** Storage for the crosshairs along the y-axis. */
088    private List<Crosshair> yCrosshairs;
089
090    /**
091     * Default constructor.
092     */
093    public CrosshairOverlay() {
094        super();
095        this.xCrosshairs = new java.util.ArrayList<Crosshair>();
096        this.yCrosshairs = new java.util.ArrayList<Crosshair>();
097    }
098
099    /**
100     * Adds a crosshair against the domain axis and sends an
101     * {@link OverlayChangeEvent} to all registered listeners.
102     *
103     * @param crosshair  the crosshair ({@code null} not permitted).
104     *
105     * @see #removeDomainCrosshair(org.jfree.chart.plot.Crosshair)
106     * @see #addRangeCrosshair(org.jfree.chart.plot.Crosshair)
107     */
108    public void addDomainCrosshair(Crosshair crosshair) {
109        Args.nullNotPermitted(crosshair, "crosshair");
110        this.xCrosshairs.add(crosshair);
111        crosshair.addPropertyChangeListener(this);
112        fireOverlayChanged();
113    }
114
115    /**
116     * Removes a domain axis crosshair and sends an {@link OverlayChangeEvent}
117     * to all registered listeners.
118     *
119     * @param crosshair  the crosshair ({@code null} not permitted).
120     *
121     * @see #addDomainCrosshair(org.jfree.chart.plot.Crosshair)
122     */
123    public void removeDomainCrosshair(Crosshair crosshair) {
124        Args.nullNotPermitted(crosshair, "crosshair");
125        if (this.xCrosshairs.remove(crosshair)) {
126            crosshair.removePropertyChangeListener(this);
127            fireOverlayChanged();
128        }
129    }
130
131    /**
132     * Clears all the domain crosshairs from the overlay and sends an
133     * {@link OverlayChangeEvent} to all registered listeners.
134     */
135    public void clearDomainCrosshairs() {
136        if (this.xCrosshairs.isEmpty()) {
137            return;  // nothing to do
138        }
139        List<Crosshair> crosshairs = getDomainCrosshairs();
140        for (Crosshair c : crosshairs) {
141            this.xCrosshairs.remove(c);
142            c.removePropertyChangeListener(this);
143        }
144        fireOverlayChanged();
145    }
146
147    /**
148     * Returns a new list containing the domain crosshairs for this overlay.
149     *
150     * @return A list of crosshairs.
151     */
152    public List<Crosshair> getDomainCrosshairs() {
153        return new ArrayList<Crosshair>(this.xCrosshairs);
154    }
155
156    /**
157     * Adds a crosshair against the range axis and sends an
158     * {@link OverlayChangeEvent} to all registered listeners.
159     *
160     * @param crosshair  the crosshair ({@code null} not permitted).
161     */
162    public void addRangeCrosshair(Crosshair crosshair) {
163        Args.nullNotPermitted(crosshair, "crosshair");
164        this.yCrosshairs.add(crosshair);
165        crosshair.addPropertyChangeListener(this);
166        fireOverlayChanged();
167    }
168
169    /**
170     * Removes a range axis crosshair and sends an {@link OverlayChangeEvent}
171     * to all registered listeners.
172     *
173     * @param crosshair  the crosshair ({@code null} not permitted).
174     *
175     * @see #addRangeCrosshair(org.jfree.chart.plot.Crosshair)
176     */
177    public void removeRangeCrosshair(Crosshair crosshair) {
178        Args.nullNotPermitted(crosshair, "crosshair");
179        if (this.yCrosshairs.remove(crosshair)) {
180            crosshair.removePropertyChangeListener(this);
181            fireOverlayChanged();
182        }
183    }
184
185    /**
186     * Clears all the range crosshairs from the overlay and sends an
187     * {@link OverlayChangeEvent} to all registered listeners.
188     */
189    public void clearRangeCrosshairs() {
190        if (this.yCrosshairs.isEmpty()) {
191            return;  // nothing to do
192        }
193        List<Crosshair> crosshairs = getRangeCrosshairs();
194        for (Crosshair c : crosshairs) {
195            this.yCrosshairs.remove(c);
196            c.removePropertyChangeListener(this);
197        }
198        fireOverlayChanged();
199    }
200
201    /**
202     * Returns a new list containing the range crosshairs for this overlay.
203     *
204     * @return A list of crosshairs.
205     */
206    public List<Crosshair> getRangeCrosshairs() {
207        return new ArrayList<Crosshair>(this.yCrosshairs);
208    }
209
210    /**
211     * Receives a property change event (typically a change in one of the
212     * crosshairs).
213     *
214     * @param e  the event.
215     */
216    @Override
217    public void propertyChange(PropertyChangeEvent e) {
218        fireOverlayChanged();
219    }
220
221    /**
222     * Paints the crosshairs in the layer.
223     *
224     * @param g2  the graphics target.
225     * @param chartPanel  the chart panel.
226     */
227    @Override
228    public void paintOverlay(Graphics2D g2, ChartPanel chartPanel) {
229        Shape savedClip = g2.getClip();
230        Rectangle2D dataArea = chartPanel.getScreenDataArea();
231        g2.clip(dataArea);
232        JFreeChart chart = chartPanel.getChart();
233        XYPlot plot = (XYPlot) chart.getPlot();
234        ValueAxis xAxis = plot.getDomainAxis();
235        RectangleEdge xAxisEdge = plot.getDomainAxisEdge();
236        Iterator<Crosshair> iterator = this.xCrosshairs.iterator();
237        while (iterator.hasNext()) {
238            Crosshair ch = iterator.next();
239            if (ch.isVisible()) {
240                double x = ch.getValue();
241                double xx = xAxis.valueToJava2D(x, dataArea, xAxisEdge);
242                if (plot.getOrientation() == PlotOrientation.VERTICAL) {
243                    drawVerticalCrosshair(g2, dataArea, xx, ch);
244                }
245                else {
246                    drawHorizontalCrosshair(g2, dataArea, xx, ch);
247                }
248            }
249        }
250        ValueAxis yAxis = plot.getRangeAxis();
251        RectangleEdge yAxisEdge = plot.getRangeAxisEdge();
252        iterator = this.yCrosshairs.iterator();
253        while (iterator.hasNext()) {
254            Crosshair ch = iterator.next();
255            if (ch.isVisible()) {
256                double y = ch.getValue();
257                double yy = yAxis.valueToJava2D(y, dataArea, yAxisEdge);
258                if (plot.getOrientation() == PlotOrientation.VERTICAL) {
259                    drawHorizontalCrosshair(g2, dataArea, yy, ch);
260                }
261                else {
262                    drawVerticalCrosshair(g2, dataArea, yy, ch);
263                }
264            }
265        }
266        g2.setClip(savedClip);
267    }
268
269    /**
270     * Draws a crosshair horizontally across the plot.
271     *
272     * @param g2  the graphics target.
273     * @param dataArea  the data area.
274     * @param y  the y-value in Java2D space.
275     * @param crosshair  the crosshair.
276     */
277    protected void drawHorizontalCrosshair(Graphics2D g2, Rectangle2D dataArea,
278            double y, Crosshair crosshair) {
279
280        if (y >= dataArea.getMinY() && y <= dataArea.getMaxY()) {
281            Line2D line = new Line2D.Double(dataArea.getMinX(), y,
282                    dataArea.getMaxX(), y);
283            Paint savedPaint = g2.getPaint();
284            Stroke savedStroke = g2.getStroke();
285            g2.setPaint(crosshair.getPaint());
286            g2.setStroke(crosshair.getStroke());
287            g2.draw(line);
288            if (crosshair.isLabelVisible()) {
289                Font savedFont = g2.getFont();
290                g2.setFont(crosshair.getLabelFont());
291                String label = crosshair.getLabelGenerator().generateLabel(
292                        crosshair);
293                RectangleAnchor anchor = crosshair.getLabelAnchor();
294                Point2D pt = calculateLabelPoint(line, anchor, 5, 5);
295                float xx = (float) pt.getX();
296                float yy = (float) pt.getY();
297                TextAnchor alignPt = textAlignPtForLabelAnchorH(anchor);
298                Shape hotspot = TextUtils.calculateRotatedStringBounds(
299                        label, g2, xx, yy, alignPt, 0.0, TextAnchor.CENTER);
300                if (!dataArea.contains(hotspot.getBounds2D())) {
301                    anchor = flipAnchorV(anchor);
302                    pt = calculateLabelPoint(line, anchor, 5, 5);
303                    xx = (float) pt.getX();
304                    yy = (float) pt.getY();
305                    alignPt = textAlignPtForLabelAnchorH(anchor);
306                    hotspot = TextUtils.calculateRotatedStringBounds(
307                           label, g2, xx, yy, alignPt, 0.0, TextAnchor.CENTER);
308                }
309
310                g2.setPaint(crosshair.getLabelBackgroundPaint());
311                g2.fill(hotspot);
312                if (crosshair.isLabelOutlineVisible()) {
313                    g2.setPaint(crosshair.getLabelOutlinePaint());
314                    g2.setStroke(crosshair.getLabelOutlineStroke());
315                }
316                g2.draw(hotspot);
317                g2.setPaint(crosshair.getLabelPaint());
318                TextUtils.drawAlignedString(label, g2, xx, yy, alignPt);
319                g2.setFont(savedFont);
320            }
321            g2.setPaint(savedPaint);
322            g2.setStroke(savedStroke);
323        }
324    }
325
326    /**
327     * Draws a crosshair vertically on the plot.
328     *
329     * @param g2  the graphics target.
330     * @param dataArea  the data area.
331     * @param x  the x-value in Java2D space.
332     * @param crosshair  the crosshair.
333     */
334    protected void drawVerticalCrosshair(Graphics2D g2, Rectangle2D dataArea,
335            double x, Crosshair crosshair) {
336
337        if (x >= dataArea.getMinX() && x <= dataArea.getMaxX()) {
338            Line2D line = new Line2D.Double(x, dataArea.getMinY(), x,
339                    dataArea.getMaxY());
340            Paint savedPaint = g2.getPaint();
341            Stroke savedStroke = g2.getStroke();
342            g2.setPaint(crosshair.getPaint());
343            g2.setStroke(crosshair.getStroke());
344            g2.draw(line);
345            if (crosshair.isLabelVisible()) {
346                Font savedFont = g2.getFont();
347                g2.setFont(crosshair.getLabelFont());
348                String label = crosshair.getLabelGenerator().generateLabel(
349                        crosshair);
350                RectangleAnchor anchor = crosshair.getLabelAnchor();
351                Point2D pt = calculateLabelPoint(line, anchor, 5, 5);
352                float xx = (float) pt.getX();
353                float yy = (float) pt.getY();
354                TextAnchor alignPt = textAlignPtForLabelAnchorV(anchor);
355                Shape hotspot = TextUtils.calculateRotatedStringBounds(
356                        label, g2, xx, yy, alignPt, 0.0, TextAnchor.CENTER);
357                if (!dataArea.contains(hotspot.getBounds2D())) {
358                    anchor = flipAnchorH(anchor);
359                    pt = calculateLabelPoint(line, anchor, 5, 5);
360                    xx = (float) pt.getX();
361                    yy = (float) pt.getY();
362                    alignPt = textAlignPtForLabelAnchorV(anchor);
363                    hotspot = TextUtils.calculateRotatedStringBounds(
364                           label, g2, xx, yy, alignPt, 0.0, TextAnchor.CENTER);
365                }
366                g2.setPaint(crosshair.getLabelBackgroundPaint());
367                g2.fill(hotspot);
368                if (crosshair.isLabelOutlineVisible()) {
369                    g2.setPaint(crosshair.getLabelOutlinePaint());
370                    g2.setStroke(crosshair.getLabelOutlineStroke());
371                    g2.draw(hotspot);
372                }
373                g2.setPaint(crosshair.getLabelPaint());
374                TextUtils.drawAlignedString(label, g2, xx, yy, alignPt);
375                g2.setFont(savedFont);
376            }
377            g2.setPaint(savedPaint);
378            g2.setStroke(savedStroke);
379        }
380    }
381
382    /**
383     * Calculates the anchor point for a label.
384     *
385     * @param line  the line for the crosshair.
386     * @param anchor  the anchor point.
387     * @param deltaX  the x-offset.
388     * @param deltaY  the y-offset.
389     *
390     * @return The anchor point.
391     */
392    private Point2D calculateLabelPoint(Line2D line, RectangleAnchor anchor,
393            double deltaX, double deltaY) {
394        double x, y;
395        boolean left = (anchor == RectangleAnchor.BOTTOM_LEFT 
396                || anchor == RectangleAnchor.LEFT 
397                || anchor == RectangleAnchor.TOP_LEFT);
398        boolean right = (anchor == RectangleAnchor.BOTTOM_RIGHT 
399                || anchor == RectangleAnchor.RIGHT 
400                || anchor == RectangleAnchor.TOP_RIGHT);
401        boolean top = (anchor == RectangleAnchor.TOP_LEFT 
402                || anchor == RectangleAnchor.TOP 
403                || anchor == RectangleAnchor.TOP_RIGHT);
404        boolean bottom = (anchor == RectangleAnchor.BOTTOM_LEFT
405                || anchor == RectangleAnchor.BOTTOM
406                || anchor == RectangleAnchor.BOTTOM_RIGHT);
407        Rectangle rect = line.getBounds();
408        
409        // we expect the line to be vertical or horizontal
410        if (line.getX1() == line.getX2()) {  // vertical
411            x = line.getX1();
412            y = (line.getY1() + line.getY2()) / 2.0;
413            if (left) {
414                x = x - deltaX;
415            }
416            if (right) {
417                x = x + deltaX;
418            }
419            if (top) {
420                y = Math.min(line.getY1(), line.getY2()) + deltaY;
421            }
422            if (bottom) {
423                y = Math.max(line.getY1(), line.getY2()) - deltaY;
424            }
425        }
426        else {  // horizontal
427            x = (line.getX1() + line.getX2()) / 2.0;
428            y = line.getY1();
429            if (left) {
430                x = Math.min(line.getX1(), line.getX2()) + deltaX;
431            }
432            if (right) {
433                x = Math.max(line.getX1(), line.getX2()) - deltaX;
434            }
435            if (top) {
436                y = y - deltaY;
437            }
438            if (bottom) {
439                y = y + deltaY;
440            }
441        }
442        return new Point2D.Double(x, y);
443    }
444
445    /**
446     * Returns the text anchor that is used to align a label to its anchor 
447     * point.
448     * 
449     * @param anchor  the anchor.
450     * 
451     * @return The text alignment point.
452     */
453    private TextAnchor textAlignPtForLabelAnchorV(RectangleAnchor anchor) {
454        TextAnchor result = TextAnchor.CENTER;
455        if (anchor.equals(RectangleAnchor.TOP_LEFT)) {
456            result = TextAnchor.TOP_RIGHT;
457        }
458        else if (anchor.equals(RectangleAnchor.TOP)) {
459            result = TextAnchor.TOP_CENTER;
460        }
461        else if (anchor.equals(RectangleAnchor.TOP_RIGHT)) {
462            result = TextAnchor.TOP_LEFT;
463        }
464        else if (anchor.equals(RectangleAnchor.LEFT)) {
465            result = TextAnchor.HALF_ASCENT_RIGHT;
466        }
467        else if (anchor.equals(RectangleAnchor.RIGHT)) {
468            result = TextAnchor.HALF_ASCENT_LEFT;
469        }
470        else if (anchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
471            result = TextAnchor.BOTTOM_RIGHT;
472        }
473        else if (anchor.equals(RectangleAnchor.BOTTOM)) {
474            result = TextAnchor.BOTTOM_CENTER;
475        }
476        else if (anchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
477            result = TextAnchor.BOTTOM_LEFT;
478        }
479        return result;
480    }
481
482    /**
483     * Returns the text anchor that is used to align a label to its anchor
484     * point.
485     *
486     * @param anchor  the anchor.
487     *
488     * @return The text alignment point.
489     */
490    private TextAnchor textAlignPtForLabelAnchorH(RectangleAnchor anchor) {
491        TextAnchor result = TextAnchor.CENTER;
492        if (anchor.equals(RectangleAnchor.TOP_LEFT)) {
493            result = TextAnchor.BOTTOM_LEFT;
494        }
495        else if (anchor.equals(RectangleAnchor.TOP)) {
496            result = TextAnchor.BOTTOM_CENTER;
497        }
498        else if (anchor.equals(RectangleAnchor.TOP_RIGHT)) {
499            result = TextAnchor.BOTTOM_RIGHT;
500        }
501        else if (anchor.equals(RectangleAnchor.LEFT)) {
502            result = TextAnchor.HALF_ASCENT_LEFT;
503        }
504        else if (anchor.equals(RectangleAnchor.RIGHT)) {
505            result = TextAnchor.HALF_ASCENT_RIGHT;
506        }
507        else if (anchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
508            result = TextAnchor.TOP_LEFT;
509        }
510        else if (anchor.equals(RectangleAnchor.BOTTOM)) {
511            result = TextAnchor.TOP_CENTER;
512        }
513        else if (anchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
514            result = TextAnchor.TOP_RIGHT;
515        }
516        return result;
517    }
518
519    private RectangleAnchor flipAnchorH(RectangleAnchor anchor) {
520        RectangleAnchor result = anchor;
521        if (anchor.equals(RectangleAnchor.TOP_LEFT)) {
522            result = RectangleAnchor.TOP_RIGHT;
523        }
524        else if (anchor.equals(RectangleAnchor.TOP_RIGHT)) {
525            result = RectangleAnchor.TOP_LEFT;
526        }
527        else if (anchor.equals(RectangleAnchor.LEFT)) {
528            result = RectangleAnchor.RIGHT;
529        }
530        else if (anchor.equals(RectangleAnchor.RIGHT)) {
531            result = RectangleAnchor.LEFT;
532        }
533        else if (anchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
534            result = RectangleAnchor.BOTTOM_RIGHT;
535        }
536        else if (anchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
537            result = RectangleAnchor.BOTTOM_LEFT;
538        }
539        return result;
540    }
541
542    private RectangleAnchor flipAnchorV(RectangleAnchor anchor) {
543        RectangleAnchor result = anchor;
544        if (anchor.equals(RectangleAnchor.TOP_LEFT)) {
545            result = RectangleAnchor.BOTTOM_LEFT;
546        }
547        else if (anchor.equals(RectangleAnchor.TOP_RIGHT)) {
548            result = RectangleAnchor.BOTTOM_RIGHT;
549        }
550        else if (anchor.equals(RectangleAnchor.TOP)) {
551            result = RectangleAnchor.BOTTOM;
552        }
553        else if (anchor.equals(RectangleAnchor.BOTTOM)) {
554            result = RectangleAnchor.TOP;
555        }
556        else if (anchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
557            result = RectangleAnchor.TOP_LEFT;
558        }
559        else if (anchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
560            result = RectangleAnchor.TOP_RIGHT;
561        }
562        return result;
563    }
564
565    /**
566     * Tests this overlay for equality with an arbitrary object.
567     *
568     * @param obj  the object ({@code null} permitted).
569     *
570     * @return A boolean.
571     */
572    @Override
573    public boolean equals(Object obj) {
574        if (obj == this) {
575            return true;
576        }
577        if (!(obj instanceof CrosshairOverlay)) {
578            return false;
579        }
580        CrosshairOverlay that = (CrosshairOverlay) obj;
581        if (!this.xCrosshairs.equals(that.xCrosshairs)) {
582            return false;
583        }
584        if (!this.yCrosshairs.equals(that.yCrosshairs)) {
585            return false;
586        }
587        return true;
588    }
589
590    /**
591     * Returns a clone of this instance.
592     *
593     * @return A clone of this instance.
594     *
595     * @throws java.lang.CloneNotSupportedException if there is some problem
596     *     with the cloning.
597     */
598    @Override
599    public Object clone() throws CloneNotSupportedException {
600        CrosshairOverlay clone = (CrosshairOverlay) super.clone();
601        clone.xCrosshairs = (List) ObjectUtils.deepClone(this.xCrosshairs);
602        clone.yCrosshairs = (List) ObjectUtils.deepClone(this.yCrosshairs);
603        return clone;
604    }
605
606}