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 * LegendTitle.java
029 * ----------------
030 * (C) Copyright 2002-2017, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Pierre-Marie Le Biot;
034 *
035 * Changes
036 * -------
037 * 25-Nov-2004 : First working version (DG);
038 * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG);
039 * 08-Feb-2005 : Updated for changes in RectangleConstraint class (DG);
040 * 11-Feb-2005 : Implemented PublicCloneable (DG);
041 * 23-Feb-2005 : Replaced chart reference with LegendItemSource (DG);
042 * 16-Mar-2005 : Added itemFont attribute (DG);
043 * 17-Mar-2005 : Fixed missing fillShape setting (DG);
044 * 20-Apr-2005 : Added new draw() method (DG);
045 * 03-May-2005 : Modified equals() method to ignore sources (DG);
046 * 13-May-2005 : Added settings for legend item label and graphic padding (DG);
047 * 09-Jun-2005 : Fixed serialization bug (DG);
048 * 01-Sep-2005 : Added itemPaint attribute (PMLB);
049 * ------------- JFREECHART 1.0.x ---------------------------------------------
050 * 20-Jul-2006 : Use new LegendItemBlockContainer to restore support for
051 *               LegendItemEntities (DG);
052 * 06-Oct-2006 : Add tooltip and URL text to legend item (DG);
053 * 13-Dec-2006 : Added support for GradientPaint in legend items (DG);
054 * 16-Mar-2007 : Updated border drawing for changes in AbstractBlock (DG);
055 * 18-May-2007 : Pass seriesKey and dataset to legend item block (DG);
056 * 15-Aug-2008 : Added getWrapper() method (DG);
057 * 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG);
058 * 11-Mar-2012 : Added sort-order support - patch 3500621 by Simon Kaczor (MH);
059 * 03-Jul-2013 : Use ParamChecks (DG);
060 * 
061 */
062
063package org.jfree.chart.title;
064
065import java.awt.Color;
066import java.awt.Font;
067import java.awt.Graphics2D;
068import java.awt.Paint;
069import java.awt.geom.Rectangle2D;
070import java.io.IOException;
071import java.io.ObjectInputStream;
072import java.io.ObjectOutputStream;
073import java.io.Serializable;
074
075import org.jfree.chart.LegendItem;
076import org.jfree.chart.LegendItemCollection;
077import org.jfree.chart.LegendItemSource;
078import org.jfree.chart.block.Arrangement;
079import org.jfree.chart.block.Block;
080import org.jfree.chart.block.BlockContainer;
081import org.jfree.chart.block.BlockFrame;
082import org.jfree.chart.block.BlockResult;
083import org.jfree.chart.block.BorderArrangement;
084import org.jfree.chart.block.CenterArrangement;
085import org.jfree.chart.block.ColumnArrangement;
086import org.jfree.chart.block.EntityBlockParams;
087import org.jfree.chart.block.FlowArrangement;
088import org.jfree.chart.block.LabelBlock;
089import org.jfree.chart.block.RectangleConstraint;
090import org.jfree.chart.entity.EntityCollection;
091import org.jfree.chart.entity.StandardEntityCollection;
092import org.jfree.chart.entity.TitleEntity;
093import org.jfree.chart.event.TitleChangeEvent;
094import org.jfree.chart.ui.RectangleAnchor;
095import org.jfree.chart.ui.RectangleEdge;
096import org.jfree.chart.util.PublicCloneable;
097import org.jfree.chart.util.SerialUtils;
098import org.jfree.chart.ui.RectangleInsets;
099import org.jfree.chart.ui.Size2D;
100import org.jfree.chart.util.PaintUtils;
101import org.jfree.chart.util.Args;
102import org.jfree.chart.util.SortOrder;
103
104
105/**
106 * A chart title that displays a legend for the data in the chart.
107 * <P>
108 * The title can be populated with legend items manually, or you can assign a
109 * reference to the plot, in which case the legend items will be automatically
110 * created to match the dataset(s).
111 */
112public class LegendTitle extends Title
113        implements Cloneable, PublicCloneable, Serializable {
114
115    /** For serialization. */
116    private static final long serialVersionUID = 2644010518533854633L;
117
118    /** The default item font. */
119    public static final Font DEFAULT_ITEM_FONT
120            = new Font("SansSerif", Font.PLAIN, 12);
121
122    /** The default item paint. */
123    public static final Paint DEFAULT_ITEM_PAINT = Color.BLACK;
124
125    /** The sources for legend items. */
126    private LegendItemSource[] sources;
127
128    /** The background paint (possibly {@code null}). */
129    private transient Paint backgroundPaint;
130
131    /** The edge for the legend item graphic relative to the text. */
132    private RectangleEdge legendItemGraphicEdge;
133
134    /** The anchor point for the legend item graphic. */
135    private RectangleAnchor legendItemGraphicAnchor;
136
137    /** The legend item graphic location. */
138    private RectangleAnchor legendItemGraphicLocation;
139
140    /** The padding for the legend item graphic. */
141    private RectangleInsets legendItemGraphicPadding;
142
143    /** The item font. */
144    private Font itemFont;
145
146    /** The item paint. */
147    private transient Paint itemPaint;
148
149    /** The padding for the item labels. */
150    private RectangleInsets itemLabelPadding;
151
152    /**
153     * A container that holds and displays the legend items.
154     */
155    private BlockContainer items;
156
157    /**
158     * The layout for the legend when it is positioned at the top or bottom
159     * of the chart.
160     */
161    private Arrangement hLayout;
162
163    /**
164     * The layout for the legend when it is positioned at the left or right
165     * of the chart.
166     */
167    private Arrangement vLayout;
168
169    /**
170     * An optional container for wrapping the legend items (allows for adding
171     * a title or other text to the legend).
172     */
173    private BlockContainer wrapper;
174
175    /**
176     * Whether to render legend items in ascending or descending order.
177     * @since 1.0.15
178     */
179    private SortOrder sortOrder;
180
181    /**
182     * Constructs a new (empty) legend for the specified source.
183     *
184     * @param source  the source.
185     */
186    public LegendTitle(LegendItemSource source) {
187        this(source, new FlowArrangement(), new ColumnArrangement());
188    }
189
190    /**
191     * Creates a new legend title with the specified arrangement.
192     *
193     * @param source  the source.
194     * @param hLayout  the horizontal item arrangement ({@code null} not
195     *                 permitted).
196     * @param vLayout  the vertical item arrangement ({@code null} not
197     *                 permitted).
198     */
199    public LegendTitle(LegendItemSource source,
200                       Arrangement hLayout, Arrangement vLayout) {
201        this.sources = new LegendItemSource[] {source};
202        this.items = new BlockContainer(hLayout);
203        this.hLayout = hLayout;
204        this.vLayout = vLayout;
205        this.backgroundPaint = null;
206        this.legendItemGraphicEdge = RectangleEdge.LEFT;
207        this.legendItemGraphicAnchor = RectangleAnchor.CENTER;
208        this.legendItemGraphicLocation = RectangleAnchor.CENTER;
209        this.legendItemGraphicPadding = new RectangleInsets(2.0, 2.0, 2.0, 2.0);
210        this.itemFont = DEFAULT_ITEM_FONT;
211        this.itemPaint = DEFAULT_ITEM_PAINT;
212        this.itemLabelPadding = new RectangleInsets(2.0, 2.0, 2.0, 2.0);
213        this.sortOrder = SortOrder.ASCENDING;
214    }
215
216    /**
217     * Returns the legend item sources.
218     *
219     * @return The sources.
220     */
221    public LegendItemSource[] getSources() {
222        return this.sources;
223    }
224
225    /**
226     * Sets the legend item sources and sends a {@link TitleChangeEvent} to
227     * all registered listeners.
228     *
229     * @param sources  the sources ({@code null} not permitted).
230     */
231    public void setSources(LegendItemSource[] sources) {
232        Args.nullNotPermitted(sources, "sources");
233        this.sources = sources;
234        notifyListeners(new TitleChangeEvent(this));
235    }
236
237    /**
238     * Returns the background paint.
239     *
240     * @return The background paint (possibly {@code null}).
241     */
242    public Paint getBackgroundPaint() {
243        return this.backgroundPaint;
244    }
245
246    /**
247     * Sets the background paint for the legend and sends a
248     * {@link TitleChangeEvent} to all registered listeners.
249     *
250     * @param paint  the paint ({@code null} permitted).
251     */
252    public void setBackgroundPaint(Paint paint) {
253        this.backgroundPaint = paint;
254        notifyListeners(new TitleChangeEvent(this));
255    }
256
257    /**
258     * Returns the location of the shape within each legend item.
259     *
260     * @return The location (never {@code null}).
261     */
262    public RectangleEdge getLegendItemGraphicEdge() {
263        return this.legendItemGraphicEdge;
264    }
265
266    /**
267     * Sets the location of the shape within each legend item.
268     *
269     * @param edge  the edge ({@code null} not permitted).
270     */
271    public void setLegendItemGraphicEdge(RectangleEdge edge) {
272        Args.nullNotPermitted(edge, "edge");
273        this.legendItemGraphicEdge = edge;
274        notifyListeners(new TitleChangeEvent(this));
275    }
276
277    /**
278     * Returns the legend item graphic anchor.
279     *
280     * @return The graphic anchor (never {@code null}).
281     */
282    public RectangleAnchor getLegendItemGraphicAnchor() {
283        return this.legendItemGraphicAnchor;
284    }
285
286    /**
287     * Sets the anchor point used for the graphic in each legend item.
288     *
289     * @param anchor  the anchor point ({@code null} not permitted).
290     */
291    public void setLegendItemGraphicAnchor(RectangleAnchor anchor) {
292        Args.nullNotPermitted(anchor, "anchor");
293        this.legendItemGraphicAnchor = anchor;
294    }
295
296    /**
297     * Returns the legend item graphic location.
298     *
299     * @return The location (never {@code null}).
300     */
301    public RectangleAnchor getLegendItemGraphicLocation() {
302        return this.legendItemGraphicLocation;
303    }
304
305    /**
306     * Sets the legend item graphic location.
307     *
308     * @param anchor  the anchor ({@code null} not permitted).
309     */
310    public void setLegendItemGraphicLocation(RectangleAnchor anchor) {
311        this.legendItemGraphicLocation = anchor;
312    }
313
314    /**
315     * Returns the padding that will be applied to each item graphic.
316     *
317     * @return The padding (never {@code null}).
318     */
319    public RectangleInsets getLegendItemGraphicPadding() {
320        return this.legendItemGraphicPadding;
321    }
322
323    /**
324     * Sets the padding that will be applied to each item graphic in the
325     * legend and sends a {@link TitleChangeEvent} to all registered listeners.
326     *
327     * @param padding  the padding ({@code null} not permitted).
328     */
329    public void setLegendItemGraphicPadding(RectangleInsets padding) {
330        Args.nullNotPermitted(padding, "padding");
331        this.legendItemGraphicPadding = padding;
332        notifyListeners(new TitleChangeEvent(this));
333    }
334
335    /**
336     * Returns the item font.
337     *
338     * @return The font (never {@code null}).
339     */
340    public Font getItemFont() {
341        return this.itemFont;
342    }
343
344    /**
345     * Sets the item font and sends a {@link TitleChangeEvent} to
346     * all registered listeners.
347     *
348     * @param font  the font ({@code null} not permitted).
349     */
350    public void setItemFont(Font font) {
351        Args.nullNotPermitted(font, "font");
352        this.itemFont = font;
353        notifyListeners(new TitleChangeEvent(this));
354    }
355
356    /**
357     * Returns the item paint.
358     *
359     * @return The paint (never {@code null}).
360     */
361    public Paint getItemPaint() {
362        return this.itemPaint;
363    }
364
365    /**
366     * Sets the item paint.
367     *
368     * @param paint  the paint ({@code null} not permitted).
369     */
370    public void setItemPaint(Paint paint) {
371        Args.nullNotPermitted(paint, "paint");
372        this.itemPaint = paint;
373        notifyListeners(new TitleChangeEvent(this));
374    }
375
376    /**
377     * Returns the padding used for the items labels.
378     *
379     * @return The padding (never {@code null}).
380     */
381    public RectangleInsets getItemLabelPadding() {
382        return this.itemLabelPadding;
383    }
384
385    /**
386     * Sets the padding used for the item labels in the legend.
387     *
388     * @param padding  the padding ({@code null} not permitted).
389     */
390    public void setItemLabelPadding(RectangleInsets padding) {
391        Args.nullNotPermitted(padding, "padding");
392        this.itemLabelPadding = padding;
393        notifyListeners(new TitleChangeEvent(this));
394    }
395
396    /**
397     * Gets the order used to display legend items.
398     * 
399     * @return The order (never {@code null}).
400     * @since 1.0.15
401     */
402    public SortOrder getSortOrder() {
403        return this.sortOrder;
404    }
405
406    /**
407     * Sets the order used to display legend items.
408     * 
409     * @param order Specifies ascending or descending order ({@code null}
410     *              not permitted).
411     * @since 1.0.15
412     */
413    public void setSortOrder(SortOrder order) {
414        Args.nullNotPermitted(order, "order");
415        this.sortOrder = order;
416        notifyListeners(new TitleChangeEvent(this));
417    }
418
419    /**
420     * Fetches the latest legend items.
421     */
422    protected void fetchLegendItems() {
423        this.items.clear();
424        RectangleEdge p = getPosition();
425        if (RectangleEdge.isTopOrBottom(p)) {
426            this.items.setArrangement(this.hLayout);
427        }
428        else {
429            this.items.setArrangement(this.vLayout);
430        }
431
432        if (this.sortOrder.equals(SortOrder.ASCENDING)) {
433            for (int s = 0; s < this.sources.length; s++) {
434                LegendItemCollection legendItems =
435                    this.sources[s].getLegendItems();
436                if (legendItems != null) {
437                    for (int i = 0; i < legendItems.getItemCount(); i++) {
438                        addItemBlock(legendItems.get(i));
439                    }
440                }
441            }
442        }
443        else {
444            for (int s = this.sources.length - 1; s >= 0; s--) {
445                LegendItemCollection legendItems =
446                    this.sources[s].getLegendItems();
447                if (legendItems != null) {
448                    for (int i = legendItems.getItemCount()-1; i >= 0; i--) {
449                        addItemBlock(legendItems.get(i));
450                    }
451                }
452            }
453        }
454    }
455
456    private void addItemBlock(LegendItem item) {
457        Block block = createLegendItemBlock(item);
458        this.items.add(block);
459    }
460
461    /**
462     * Creates a legend item block.
463     *
464     * @param item  the legend item.
465     *
466     * @return The block.
467     */
468    protected Block createLegendItemBlock(LegendItem item) {
469        BlockContainer result;
470        LegendGraphic lg = new LegendGraphic(item.getShape(),
471                item.getFillPaint());
472        lg.setFillPaintTransformer(item.getFillPaintTransformer());
473        lg.setShapeFilled(item.isShapeFilled());
474        lg.setLine(item.getLine());
475        lg.setLineStroke(item.getLineStroke());
476        lg.setLinePaint(item.getLinePaint());
477        lg.setLineVisible(item.isLineVisible());
478        lg.setShapeVisible(item.isShapeVisible());
479        lg.setShapeOutlineVisible(item.isShapeOutlineVisible());
480        lg.setOutlinePaint(item.getOutlinePaint());
481        lg.setOutlineStroke(item.getOutlineStroke());
482        lg.setPadding(this.legendItemGraphicPadding);
483
484        LegendItemBlockContainer legendItem = new LegendItemBlockContainer(
485                new BorderArrangement(), item.getDataset(),
486                item.getSeriesKey());
487        lg.setShapeAnchor(getLegendItemGraphicAnchor());
488        lg.setShapeLocation(getLegendItemGraphicLocation());
489        legendItem.add(lg, this.legendItemGraphicEdge);
490        Font textFont = item.getLabelFont();
491        if (textFont == null) {
492            textFont = this.itemFont;
493        }
494        Paint textPaint = item.getLabelPaint();
495        if (textPaint == null) {
496            textPaint = this.itemPaint;
497        }
498        LabelBlock labelBlock = new LabelBlock(item.getLabel(), textFont,
499                textPaint);
500        labelBlock.setPadding(this.itemLabelPadding);
501        legendItem.add(labelBlock);
502        legendItem.setToolTipText(item.getToolTipText());
503        legendItem.setURLText(item.getURLText());
504
505        result = new BlockContainer(new CenterArrangement());
506        result.add(legendItem);
507
508        return result;
509    }
510
511    /**
512     * Returns the container that holds the legend items.
513     *
514     * @return The container for the legend items.
515     */
516    public BlockContainer getItemContainer() {
517        return this.items;
518    }
519
520    /**
521     * Arranges the contents of the block, within the given constraints, and
522     * returns the block size.
523     *
524     * @param g2  the graphics device.
525     * @param constraint  the constraint ({@code null} not permitted).
526     *
527     * @return The block size (in Java2D units, never {@code null}).
528     */
529    @Override
530    public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) {
531        Size2D result = new Size2D();
532        fetchLegendItems();
533        if (this.items.isEmpty()) {
534            return result;
535        }
536        BlockContainer container = this.wrapper;
537        if (container == null) {
538            container = this.items;
539        }
540        RectangleConstraint c = toContentConstraint(constraint);
541        Size2D size = container.arrange(g2, c);
542        result.height = calculateTotalHeight(size.height);
543        result.width = calculateTotalWidth(size.width);
544        return result;
545    }
546
547    /**
548     * Draws the title on a Java 2D graphics device (such as the screen or a
549     * printer).
550     *
551     * @param g2  the graphics device.
552     * @param area  the available area for the title.
553     */
554    @Override
555    public void draw(Graphics2D g2, Rectangle2D area) {
556        draw(g2, area, null);
557    }
558
559    /**
560     * Draws the block within the specified area.
561     *
562     * @param g2  the graphics device.
563     * @param area  the area.
564     * @param params  ignored ({@code null} permitted).
565     *
566     * @return An {@link org.jfree.chart.block.EntityBlockResult} or
567     *         {@code null}.
568     */
569    @Override
570    public Object draw(Graphics2D g2, Rectangle2D area, Object params) {
571        Rectangle2D target = (Rectangle2D) area.clone();
572        Rectangle2D hotspot = (Rectangle2D) area.clone();
573        StandardEntityCollection sec = null;
574        if (params instanceof EntityBlockParams
575                && ((EntityBlockParams) params).getGenerateEntities()) {
576            sec = new StandardEntityCollection();
577            sec.add(new TitleEntity(hotspot, this));
578        }
579        target = trimMargin(target);
580        if (this.backgroundPaint != null) {
581            g2.setPaint(this.backgroundPaint);
582            g2.fill(target);
583        }
584        BlockFrame border = getFrame();
585        border.draw(g2, target);
586        border.getInsets().trim(target);
587        BlockContainer container = this.wrapper;
588        if (container == null) {
589            container = this.items;
590        }
591        target = trimPadding(target);
592        Object val = container.draw(g2, target, params);
593        if (val instanceof BlockResult) {
594            EntityCollection ec = ((BlockResult) val).getEntityCollection();
595            if (ec != null && sec != null) {
596                sec.addAll(ec);
597                ((BlockResult) val).setEntityCollection(sec);
598            }
599        }
600        return val;
601    }
602
603    /**
604     * Returns the wrapper container, if any.
605     *
606     * @return The wrapper container (possibly {@code null}).
607     *
608     * @since 1.0.11
609     */
610    public BlockContainer getWrapper() {
611        return this.wrapper;
612    }
613
614    /**
615     * Sets the wrapper container for the legend.
616     *
617     * @param wrapper  the wrapper container.
618     */
619    public void setWrapper(BlockContainer wrapper) {
620        this.wrapper = wrapper;
621    }
622
623    /**
624     * Tests this title for equality with an arbitrary object.
625     *
626     * @param obj  the object ({@code null} permitted).
627     *
628     * @return A boolean.
629     */
630    @Override
631    public boolean equals(Object obj) {
632        if (obj == this) {
633            return true;
634        }
635        if (!(obj instanceof LegendTitle)) {
636            return false;
637        }
638        if (!super.equals(obj)) {
639            return false;
640        }
641        LegendTitle that = (LegendTitle) obj;
642        if (!PaintUtils.equal(this.backgroundPaint, that.backgroundPaint)) {
643            return false;
644        }
645        if (this.legendItemGraphicEdge != that.legendItemGraphicEdge) {
646            return false;
647        }
648        if (this.legendItemGraphicAnchor != that.legendItemGraphicAnchor) {
649            return false;
650        }
651        if (this.legendItemGraphicLocation != that.legendItemGraphicLocation) {
652            return false;
653        }
654        if (!this.itemFont.equals(that.itemFont)) {
655            return false;
656        }
657        if (!this.itemPaint.equals(that.itemPaint)) {
658            return false;
659        }
660        if (!this.hLayout.equals(that.hLayout)) {
661            return false;
662        }
663        if (!this.vLayout.equals(that.vLayout)) {
664            return false;
665        }
666        if (!this.sortOrder.equals(that.sortOrder)) {
667            return false;
668        }
669        return true;
670    }
671
672    /**
673     * Provides serialization support.
674     *
675     * @param stream  the output stream.
676     *
677     * @throws IOException  if there is an I/O error.
678     */
679    private void writeObject(ObjectOutputStream stream) throws IOException {
680        stream.defaultWriteObject();
681        SerialUtils.writePaint(this.backgroundPaint, stream);
682        SerialUtils.writePaint(this.itemPaint, stream);
683    }
684
685    /**
686     * Provides serialization support.
687     *
688     * @param stream  the input stream.
689     *
690     * @throws IOException  if there is an I/O error.
691     * @throws ClassNotFoundException  if there is a classpath problem.
692     */
693    private void readObject(ObjectInputStream stream)
694        throws IOException, ClassNotFoundException {
695        stream.defaultReadObject();
696        this.backgroundPaint = SerialUtils.readPaint(stream);
697        this.itemPaint = SerialUtils.readPaint(stream);
698    }
699
700}