001    /* ===========================================================
002     * JFreeChart : a free chart library for the Java(tm) platform
003     * ===========================================================
004     *
005     * (C) Copyright 2000-2008, 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     * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
025     * in the United States and other countries.]
026     *
027     * --------------------
028     * MultiplePiePlot.java
029     * --------------------
030     * (C) Copyright 2004-2008, by Object Refinery Limited.
031     *
032     * Original Author:  David Gilbert (for Object Refinery Limited);
033     * Contributor(s):   Brian Cabana (patch 1943021);
034     *
035     * Changes
036     * -------
037     * 29-Jan-2004 : Version 1 (DG);
038     * 31-Mar-2004 : Added setPieIndex() call during drawing (DG);
039     * 20-Apr-2005 : Small change for update to LegendItem constructors (DG);
040     * 05-May-2005 : Updated draw() method parameters (DG);
041     * 16-Jun-2005 : Added get/setDataset() and equals() methods (DG);
042     * ------------- JFREECHART 1.0.x ---------------------------------------------
043     * 06-Apr-2006 : Fixed bug 1190647 - legend and section colors not consistent
044     *               when aggregation limit is specified (DG);
045     * 27-Sep-2006 : Updated draw() method for deprecated code (DG);
046     * 17-Jan-2007 : Updated prefetchSectionPaints() to check settings in
047     *               underlying PiePlot (DG);
048     * 17-May-2007 : Added argument check to setPieChart() (DG);
049     * 18-May-2007 : Set dataset for LegendItem (DG);
050     * 18-Apr-2008 : In the constructor, register the plot as a dataset listener -
051     *               see patch 1943021 from Brian Cabana (DG);
052     * 30-Dec-2008 : Added legendItemShape field, and fixed cloning bug (DG);
053     *
054     */
055    
056    package org.jfree.chart.plot;
057    
058    import java.awt.Color;
059    import java.awt.Font;
060    import java.awt.Graphics2D;
061    import java.awt.Paint;
062    import java.awt.Rectangle;
063    import java.awt.Shape;
064    import java.awt.geom.Ellipse2D;
065    import java.awt.geom.Point2D;
066    import java.awt.geom.Rectangle2D;
067    import java.io.IOException;
068    import java.io.ObjectInputStream;
069    import java.io.ObjectOutputStream;
070    import java.io.Serializable;
071    import java.util.HashMap;
072    import java.util.Iterator;
073    import java.util.List;
074    import java.util.Map;
075    
076    import org.jfree.chart.ChartRenderingInfo;
077    import org.jfree.chart.JFreeChart;
078    import org.jfree.chart.LegendItem;
079    import org.jfree.chart.LegendItemCollection;
080    import org.jfree.chart.event.PlotChangeEvent;
081    import org.jfree.chart.title.TextTitle;
082    import org.jfree.data.category.CategoryDataset;
083    import org.jfree.data.category.CategoryToPieDataset;
084    import org.jfree.data.general.DatasetChangeEvent;
085    import org.jfree.data.general.DatasetUtilities;
086    import org.jfree.data.general.PieDataset;
087    import org.jfree.io.SerialUtilities;
088    import org.jfree.ui.RectangleEdge;
089    import org.jfree.ui.RectangleInsets;
090    import org.jfree.util.ObjectUtilities;
091    import org.jfree.util.PaintUtilities;
092    import org.jfree.util.ShapeUtilities;
093    import org.jfree.util.TableOrder;
094    
095    /**
096     * A plot that displays multiple pie plots using data from a
097     * {@link CategoryDataset}.
098     */
099    public class MultiplePiePlot extends Plot implements Cloneable, Serializable {
100    
101        /** For serialization. */
102        private static final long serialVersionUID = -355377800470807389L;
103    
104        /** The chart object that draws the individual pie charts. */
105        private JFreeChart pieChart;
106    
107        /** The dataset. */
108        private CategoryDataset dataset;
109    
110        /** The data extract order (by row or by column). */
111        private TableOrder dataExtractOrder;
112    
113        /** The pie section limit percentage. */
114        private double limit = 0.0;
115    
116        /**
117         * The key for the aggregated items.
118         * @since 1.0.2
119         */
120        private Comparable aggregatedItemsKey;
121    
122        /**
123         * The paint for the aggregated items.
124         * @since 1.0.2
125         */
126        private transient Paint aggregatedItemsPaint;
127    
128        /**
129         * The colors to use for each section.
130         * @since 1.0.2
131         */
132        private transient Map sectionPaints;
133    
134        /**
135         * The legend item shape (never null).
136         * @since 1.0.12
137         */
138        private transient Shape legendItemShape;
139    
140        /**
141         * Creates a new plot with no data.
142         */
143        public MultiplePiePlot() {
144            this(null);
145        }
146    
147        /**
148         * Creates a new plot.
149         *
150         * @param dataset  the dataset (<code>null</code> permitted).
151         */
152        public MultiplePiePlot(CategoryDataset dataset) {
153            super();
154            setDataset(dataset);
155            PiePlot piePlot = new PiePlot(null);
156            this.pieChart = new JFreeChart(piePlot);
157            this.pieChart.removeLegend();
158            this.dataExtractOrder = TableOrder.BY_COLUMN;
159            this.pieChart.setBackgroundPaint(null);
160            TextTitle seriesTitle = new TextTitle("Series Title",
161                    new Font("SansSerif", Font.BOLD, 12));
162            seriesTitle.setPosition(RectangleEdge.BOTTOM);
163            this.pieChart.setTitle(seriesTitle);
164            this.aggregatedItemsKey = "Other";
165            this.aggregatedItemsPaint = Color.lightGray;
166            this.sectionPaints = new HashMap();
167            this.legendItemShape = new Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0);
168        }
169    
170        /**
171         * Returns the dataset used by the plot.
172         *
173         * @return The dataset (possibly <code>null</code>).
174         */
175        public CategoryDataset getDataset() {
176            return this.dataset;
177        }
178    
179        /**
180         * Sets the dataset used by the plot and sends a {@link PlotChangeEvent}
181         * to all registered listeners.
182         *
183         * @param dataset  the dataset (<code>null</code> permitted).
184         */
185        public void setDataset(CategoryDataset dataset) {
186            // if there is an existing dataset, remove the plot from the list of
187            // change listeners...
188            if (this.dataset != null) {
189                this.dataset.removeChangeListener(this);
190            }
191    
192            // set the new dataset, and register the chart as a change listener...
193            this.dataset = dataset;
194            if (dataset != null) {
195                setDatasetGroup(dataset.getGroup());
196                dataset.addChangeListener(this);
197            }
198    
199            // send a dataset change event to self to trigger plot change event
200            datasetChanged(new DatasetChangeEvent(this, dataset));
201        }
202    
203        /**
204         * Returns the pie chart that is used to draw the individual pie plots.
205         * Note that there are some attributes on this chart instance that will
206         * be ignored at rendering time (for example, legend item settings).
207         *
208         * @return The pie chart (never <code>null</code>).
209         *
210         * @see #setPieChart(JFreeChart)
211         */
212        public JFreeChart getPieChart() {
213            return this.pieChart;
214        }
215    
216        /**
217         * Sets the chart that is used to draw the individual pie plots.  The
218         * chart's plot must be an instance of {@link PiePlot}.
219         *
220         * @param pieChart  the pie chart (<code>null</code> not permitted).
221         *
222         * @see #getPieChart()
223         */
224        public void setPieChart(JFreeChart pieChart) {
225            if (pieChart == null) {
226                throw new IllegalArgumentException("Null 'pieChart' argument.");
227            }
228            if (!(pieChart.getPlot() instanceof PiePlot)) {
229                throw new IllegalArgumentException("The 'pieChart' argument must "
230                        + "be a chart based on a PiePlot.");
231            }
232            this.pieChart = pieChart;
233            fireChangeEvent();
234        }
235    
236        /**
237         * Returns the data extract order (by row or by column).
238         *
239         * @return The data extract order (never <code>null</code>).
240         */
241        public TableOrder getDataExtractOrder() {
242            return this.dataExtractOrder;
243        }
244    
245        /**
246         * Sets the data extract order (by row or by column) and sends a
247         * {@link PlotChangeEvent} to all registered listeners.
248         *
249         * @param order  the order (<code>null</code> not permitted).
250         */
251        public void setDataExtractOrder(TableOrder order) {
252            if (order == null) {
253                throw new IllegalArgumentException("Null 'order' argument");
254            }
255            this.dataExtractOrder = order;
256            fireChangeEvent();
257        }
258    
259        /**
260         * Returns the limit (as a percentage) below which small pie sections are
261         * aggregated.
262         *
263         * @return The limit percentage.
264         */
265        public double getLimit() {
266            return this.limit;
267        }
268    
269        /**
270         * Sets the limit below which pie sections are aggregated.
271         * Set this to 0.0 if you don't want any aggregation to occur.
272         *
273         * @param limit  the limit percent.
274         */
275        public void setLimit(double limit) {
276            this.limit = limit;
277            fireChangeEvent();
278        }
279    
280        /**
281         * Returns the key for aggregated items in the pie plots, if there are any.
282         * The default value is "Other".
283         *
284         * @return The aggregated items key.
285         *
286         * @since 1.0.2
287         */
288        public Comparable getAggregatedItemsKey() {
289            return this.aggregatedItemsKey;
290        }
291    
292        /**
293         * Sets the key for aggregated items in the pie plots.  You must ensure
294         * that this doesn't clash with any keys in the dataset.
295         *
296         * @param key  the key (<code>null</code> not permitted).
297         *
298         * @since 1.0.2
299         */
300        public void setAggregatedItemsKey(Comparable key) {
301            if (key == null) {
302                throw new IllegalArgumentException("Null 'key' argument.");
303            }
304            this.aggregatedItemsKey = key;
305            fireChangeEvent();
306        }
307    
308        /**
309         * Returns the paint used to draw the pie section representing the
310         * aggregated items.  The default value is <code>Color.lightGray</code>.
311         *
312         * @return The paint.
313         *
314         * @since 1.0.2
315         */
316        public Paint getAggregatedItemsPaint() {
317            return this.aggregatedItemsPaint;
318        }
319    
320        /**
321         * Sets the paint used to draw the pie section representing the aggregated
322         * items and sends a {@link PlotChangeEvent} to all registered listeners.
323         *
324         * @param paint  the paint (<code>null</code> not permitted).
325         *
326         * @since 1.0.2
327         */
328        public void setAggregatedItemsPaint(Paint paint) {
329            if (paint == null) {
330                throw new IllegalArgumentException("Null 'paint' argument.");
331            }
332            this.aggregatedItemsPaint = paint;
333            fireChangeEvent();
334        }
335    
336        /**
337         * Returns a short string describing the type of plot.
338         *
339         * @return The plot type.
340         */
341        public String getPlotType() {
342            return "Multiple Pie Plot";
343             // TODO: need to fetch this from localised resources
344        }
345    
346        /**
347         * Returns the shape used for legend items.
348         *
349         * @return The shape (never <code>null</code>).
350         *
351         * @see #setLegendItemShape(Shape)
352         *
353         * @since 1.0.12
354         */
355        public Shape getLegendItemShape() {
356            return this.legendItemShape;
357        }
358    
359        /**
360         * Sets the shape used for legend items and sends a {@link PlotChangeEvent}
361         * to all registered listeners.
362         *
363         * @param shape  the shape (<code>null</code> not permitted).
364         *
365         * @see #getLegendItemShape()
366         *
367         * @since 1.0.12
368         */
369        public void setLegendItemShape(Shape shape) {
370            if (shape == null) {
371                throw new IllegalArgumentException("Null 'shape' argument.");
372            }
373            this.legendItemShape = shape;
374            fireChangeEvent();
375        }
376    
377        /**
378         * Draws the plot on a Java 2D graphics device (such as the screen or a
379         * printer).
380         *
381         * @param g2  the graphics device.
382         * @param area  the area within which the plot should be drawn.
383         * @param anchor  the anchor point (<code>null</code> permitted).
384         * @param parentState  the state from the parent plot, if there is one.
385         * @param info  collects info about the drawing.
386         */
387        public void draw(Graphics2D g2,
388                         Rectangle2D area,
389                         Point2D anchor,
390                         PlotState parentState,
391                         PlotRenderingInfo info) {
392    
393    
394            // adjust the drawing area for the plot insets (if any)...
395            RectangleInsets insets = getInsets();
396            insets.trim(area);
397            drawBackground(g2, area);
398            drawOutline(g2, area);
399    
400            // check that there is some data to display...
401            if (DatasetUtilities.isEmptyOrNull(this.dataset)) {
402                drawNoDataMessage(g2, area);
403                return;
404            }
405    
406            int pieCount = 0;
407            if (this.dataExtractOrder == TableOrder.BY_ROW) {
408                pieCount = this.dataset.getRowCount();
409            }
410            else {
411                pieCount = this.dataset.getColumnCount();
412            }
413    
414            // the columns variable is always >= rows
415            int displayCols = (int) Math.ceil(Math.sqrt(pieCount));
416            int displayRows
417                = (int) Math.ceil((double) pieCount / (double) displayCols);
418    
419            // swap rows and columns to match plotArea shape
420            if (displayCols > displayRows && area.getWidth() < area.getHeight()) {
421                int temp = displayCols;
422                displayCols = displayRows;
423                displayRows = temp;
424            }
425    
426            prefetchSectionPaints();
427    
428            int x = (int) area.getX();
429            int y = (int) area.getY();
430            int width = ((int) area.getWidth()) / displayCols;
431            int height = ((int) area.getHeight()) / displayRows;
432            int row = 0;
433            int column = 0;
434            int diff = (displayRows * displayCols) - pieCount;
435            int xoffset = 0;
436            Rectangle rect = new Rectangle();
437    
438            for (int pieIndex = 0; pieIndex < pieCount; pieIndex++) {
439                rect.setBounds(x + xoffset + (width * column), y + (height * row),
440                        width, height);
441    
442                String title = null;
443                if (this.dataExtractOrder == TableOrder.BY_ROW) {
444                    title = this.dataset.getRowKey(pieIndex).toString();
445                }
446                else {
447                    title = this.dataset.getColumnKey(pieIndex).toString();
448                }
449                this.pieChart.setTitle(title);
450    
451                PieDataset piedataset = null;
452                PieDataset dd = new CategoryToPieDataset(this.dataset,
453                        this.dataExtractOrder, pieIndex);
454                if (this.limit > 0.0) {
455                    piedataset = DatasetUtilities.createConsolidatedPieDataset(
456                            dd, this.aggregatedItemsKey, this.limit);
457                }
458                else {
459                    piedataset = dd;
460                }
461                PiePlot piePlot = (PiePlot) this.pieChart.getPlot();
462                piePlot.setDataset(piedataset);
463                piePlot.setPieIndex(pieIndex);
464    
465                // update the section colors to match the global colors...
466                for (int i = 0; i < piedataset.getItemCount(); i++) {
467                    Comparable key = piedataset.getKey(i);
468                    Paint p;
469                    if (key.equals(this.aggregatedItemsKey)) {
470                        p = this.aggregatedItemsPaint;
471                    }
472                    else {
473                        p = (Paint) this.sectionPaints.get(key);
474                    }
475                    piePlot.setSectionPaint(key, p);
476                }
477    
478                ChartRenderingInfo subinfo = null;
479                if (info != null) {
480                    subinfo = new ChartRenderingInfo();
481                }
482                this.pieChart.draw(g2, rect, subinfo);
483                if (info != null) {
484                    info.getOwner().getEntityCollection().addAll(
485                            subinfo.getEntityCollection());
486                    info.addSubplotInfo(subinfo.getPlotInfo());
487                }
488    
489                ++column;
490                if (column == displayCols) {
491                    column = 0;
492                    ++row;
493    
494                    if (row == displayRows - 1 && diff != 0) {
495                        xoffset = (diff * width) / 2;
496                    }
497                }
498            }
499    
500        }
501    
502        /**
503         * For each key in the dataset, check the <code>sectionPaints</code>
504         * cache to see if a paint is associated with that key and, if not,
505         * fetch one from the drawing supplier.  These colors are cached so that
506         * the legend and all the subplots use consistent colors.
507         */
508        private void prefetchSectionPaints() {
509    
510            // pre-fetch the colors for each key...this is because the subplots
511            // may not display every key, but we need the coloring to be
512            // consistent...
513    
514            PiePlot piePlot = (PiePlot) getPieChart().getPlot();
515    
516            if (this.dataExtractOrder == TableOrder.BY_ROW) {
517                // column keys provide potential keys for individual pies
518                for (int c = 0; c < this.dataset.getColumnCount(); c++) {
519                    Comparable key = this.dataset.getColumnKey(c);
520                    Paint p = piePlot.getSectionPaint(key);
521                    if (p == null) {
522                        p = (Paint) this.sectionPaints.get(key);
523                        if (p == null) {
524                            p = getDrawingSupplier().getNextPaint();
525                        }
526                    }
527                    this.sectionPaints.put(key, p);
528                }
529            }
530            else {
531                // row keys provide potential keys for individual pies
532                for (int r = 0; r < this.dataset.getRowCount(); r++) {
533                    Comparable key = this.dataset.getRowKey(r);
534                    Paint p = piePlot.getSectionPaint(key);
535                    if (p == null) {
536                        p = (Paint) this.sectionPaints.get(key);
537                        if (p == null) {
538                            p = getDrawingSupplier().getNextPaint();
539                        }
540                    }
541                    this.sectionPaints.put(key, p);
542                }
543            }
544    
545        }
546    
547        /**
548         * Returns a collection of legend items for the pie chart.
549         *
550         * @return The legend items.
551         */
552        public LegendItemCollection getLegendItems() {
553    
554            LegendItemCollection result = new LegendItemCollection();
555            if (this.dataset == null) {
556                return result;
557            }
558    
559            List keys = null;
560            prefetchSectionPaints();
561            if (this.dataExtractOrder == TableOrder.BY_ROW) {
562                keys = this.dataset.getColumnKeys();
563            }
564            else if (this.dataExtractOrder == TableOrder.BY_COLUMN) {
565                keys = this.dataset.getRowKeys();
566            }
567    
568            if (keys != null) {
569                int section = 0;
570                Iterator iterator = keys.iterator();
571                while (iterator.hasNext()) {
572                    Comparable key = (Comparable) iterator.next();
573                    String label = key.toString();  // TODO: use a generator here
574                    String description = label;
575                    Paint paint = (Paint) this.sectionPaints.get(key);
576                    LegendItem item = new LegendItem(label, description, null,
577                            null, getLegendItemShape(), paint,
578                            Plot.DEFAULT_OUTLINE_STROKE, paint);
579                    item.setDataset(getDataset());
580                    result.add(item);
581                    section++;
582                }
583            }
584            if (this.limit > 0.0) {
585                result.add(new LegendItem(this.aggregatedItemsKey.toString(),
586                        this.aggregatedItemsKey.toString(), null, null,
587                        getLegendItemShape(), this.aggregatedItemsPaint,
588                        Plot.DEFAULT_OUTLINE_STROKE, this.aggregatedItemsPaint));
589            }
590            return result;
591        }
592    
593        /**
594         * Tests this plot for equality with an arbitrary object.  Note that the
595         * plot's dataset is not considered in the equality test.
596         *
597         * @param obj  the object (<code>null</code> permitted).
598         *
599         * @return <code>true</code> if this plot is equal to <code>obj</code>, and
600         *     <code>false</code> otherwise.
601         */
602        public boolean equals(Object obj) {
603            if (obj == this) {
604                return true;
605            }
606            if (!(obj instanceof MultiplePiePlot)) {
607                return false;
608            }
609            MultiplePiePlot that = (MultiplePiePlot) obj;
610            if (this.dataExtractOrder != that.dataExtractOrder) {
611                return false;
612            }
613            if (this.limit != that.limit) {
614                return false;
615            }
616            if (!this.aggregatedItemsKey.equals(that.aggregatedItemsKey)) {
617                return false;
618            }
619            if (!PaintUtilities.equal(this.aggregatedItemsPaint,
620                    that.aggregatedItemsPaint)) {
621                return false;
622            }
623            if (!ObjectUtilities.equal(this.pieChart, that.pieChart)) {
624                return false;
625            }
626            if (!ShapeUtilities.equal(this.legendItemShape, that.legendItemShape)) {
627                return false;
628            }
629            if (!super.equals(obj)) {
630                return false;
631            }
632            return true;
633        }
634    
635        /**
636         * Returns a clone of the plot.
637         *
638         * @return A clone.
639         *
640         * @throws CloneNotSupportedException if some component of the plot does
641         *         not support cloning.
642         */
643        public Object clone() throws CloneNotSupportedException {
644            MultiplePiePlot clone = (MultiplePiePlot) super.clone();
645            clone.pieChart = (JFreeChart) this.pieChart.clone();
646            clone.sectionPaints = new HashMap(this.sectionPaints);
647            clone.legendItemShape = ShapeUtilities.clone(this.legendItemShape);
648            return clone;
649        }
650    
651        /**
652         * Provides serialization support.
653         *
654         * @param stream  the output stream.
655         *
656         * @throws IOException  if there is an I/O error.
657         */
658        private void writeObject(ObjectOutputStream stream) throws IOException {
659            stream.defaultWriteObject();
660            SerialUtilities.writePaint(this.aggregatedItemsPaint, stream);
661            SerialUtilities.writeShape(this.legendItemShape, stream);
662        }
663    
664        /**
665         * Provides serialization support.
666         *
667         * @param stream  the input stream.
668         *
669         * @throws IOException  if there is an I/O error.
670         * @throws ClassNotFoundException  if there is a classpath problem.
671         */
672        private void readObject(ObjectInputStream stream)
673            throws IOException, ClassNotFoundException {
674            stream.defaultReadObject();
675            this.aggregatedItemsPaint = SerialUtilities.readPaint(stream);
676            this.legendItemShape = SerialUtilities.readShape(stream);
677            this.sectionPaints = new HashMap();
678        }
679    
680    
681    }