001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, 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 * AbstractBlock.java
029 * ------------------
030 * (C) Copyright 2004-2016, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   -;
034 *
035 * Changes:
036 * --------
037 * 22-Oct-2004 : Version 1 (DG);
038 * 02-Feb-2005 : Added accessor methods for margin (DG);
039 * 04-Feb-2005 : Added equals() method and implemented Serializable (DG);
040 * 03-May-2005 : Added null argument checks (DG);
041 * 06-May-2005 : Added convenience methods for setting margin, border and
042 *               padding (DG);
043 * ------------- JFREECHART 1.0.x ---------------------------------------------
044 * 16-Mar-2007 : Changed border from BlockBorder to BlockFrame, updated
045 *               equals(), and implemented Cloneable (DG);
046 * 02-Jul-2013 : Use ParamChecks (DG);
047 *
048 */
049
050package org.jfree.chart.block;
051
052import java.awt.Graphics2D;
053import java.awt.geom.Rectangle2D;
054import java.io.IOException;
055import java.io.ObjectInputStream;
056import java.io.ObjectOutputStream;
057import java.io.Serializable;
058import org.jfree.chart.ui.RectangleInsets;
059import org.jfree.chart.ui.Size2D;
060import org.jfree.chart.util.ObjectUtils;
061import org.jfree.chart.util.Args;
062import org.jfree.chart.util.PublicCloneable;
063import org.jfree.chart.util.SerialUtils;
064import org.jfree.chart.util.ShapeUtils;
065
066import org.jfree.data.Range;
067
068/**
069 * A convenience class for creating new classes that implement
070 * the {@link Block} interface.
071 */
072public class AbstractBlock implements Cloneable, Serializable {
073
074    /** For serialization. */
075    private static final long serialVersionUID = 7689852412141274563L;
076
077    /** The id for the block. */
078    private String id;
079
080    /** The margin around the outside of the block. */
081    private RectangleInsets margin;
082
083    /** The frame (or border) for the block. */
084    private BlockFrame frame;
085
086    /** The padding between the block content and the border. */
087    private RectangleInsets padding;
088
089    /**
090     * The natural width of the block (may be overridden if there are
091     * constraints in sizing).
092     */
093    private double width;
094
095    /**
096     * The natural height of the block (may be overridden if there are
097     * constraints in sizing).
098     */
099    private double height;
100
101    /**
102     * The current bounds for the block (position of the block in Java2D space).
103     */
104    private transient Rectangle2D bounds;
105
106    /**
107     * Creates a new block.
108     */
109    protected AbstractBlock() {
110        this.id = null;
111        this.width = 0.0;
112        this.height = 0.0;
113        this.bounds = new Rectangle2D.Float();
114        this.margin = RectangleInsets.ZERO_INSETS;
115        this.frame = BlockBorder.NONE;
116        this.padding = RectangleInsets.ZERO_INSETS;
117    }
118
119    /**
120     * Returns the id.
121     *
122     * @return The id (possibly {@code null}).
123     *
124     * @see #setID(String)
125     */
126    public String getID() {
127        return this.id;
128    }
129
130    /**
131     * Sets the id for the block.
132     *
133     * @param id  the id ({@code null} permitted).
134     *
135     * @see #getID()
136     */
137    public void setID(String id) {
138        this.id = id;
139    }
140
141    /**
142     * Returns the natural width of the block, if this is known in advance.
143     * The actual width of the block may be overridden if layout constraints
144     * make this necessary.
145     *
146     * @return The width.
147     *
148     * @see #setWidth(double)
149     */
150    public double getWidth() {
151        return this.width;
152    }
153
154    /**
155     * Sets the natural width of the block, if this is known in advance.
156     *
157     * @param width  the width (in Java2D units)
158     *
159     * @see #getWidth()
160     */
161    public void setWidth(double width) {
162        this.width = width;
163    }
164
165    /**
166     * Returns the natural height of the block, if this is known in advance.
167     * The actual height of the block may be overridden if layout constraints
168     * make this necessary.
169     *
170     * @return The height.
171     *
172     * @see #setHeight(double)
173     */
174    public double getHeight() {
175        return this.height;
176    }
177
178    /**
179     * Sets the natural width of the block, if this is known in advance.
180     *
181     * @param height  the width (in Java2D units)
182     *
183     * @see #getHeight()
184     */
185    public void setHeight(double height) {
186        this.height = height;
187    }
188
189    /**
190     * Returns the margin.
191     *
192     * @return The margin (never {@code null}).
193     *
194     * @see #getMargin()
195     */
196    public RectangleInsets getMargin() {
197        return this.margin;
198    }
199
200    /**
201     * Sets the margin (use {@link RectangleInsets#ZERO_INSETS} for no
202     * padding).
203     *
204     * @param margin  the margin ({@code null} not permitted).
205     *
206     * @see #getMargin()
207     */
208    public void setMargin(RectangleInsets margin) {
209        Args.nullNotPermitted(margin, "margin");
210        this.margin = margin;
211    }
212
213    /**
214     * Sets the margin.
215     *
216     * @param top  the top margin.
217     * @param left  the left margin.
218     * @param bottom  the bottom margin.
219     * @param right  the right margin.
220     *
221     * @see #getMargin()
222     */
223    public void setMargin(double top, double left, double bottom, 
224            double right) {
225        setMargin(new RectangleInsets(top, left, bottom, right));
226    }
227
228    /**
229     * Sets a black border with the specified line widths.
230     *
231     * @param top  the top border line width.
232     * @param left  the left border line width.
233     * @param bottom  the bottom border line width.
234     * @param right  the right border line width.
235     */
236    public void setBorder(double top, double left, double bottom,
237                          double right) {
238        setFrame(new BlockBorder(top, left, bottom, right));
239    }
240
241    /**
242     * Returns the current frame (border).
243     *
244     * @return The frame.
245     *
246     * @since 1.0.5
247     * @see #setFrame(BlockFrame)
248     */
249    public BlockFrame getFrame() {
250        return this.frame;
251    }
252
253    /**
254     * Sets the frame (or border).
255     *
256     * @param frame  the frame ({@code null} not permitted).
257     *
258     * @since 1.0.5
259     * @see #getFrame()
260     */
261    public void setFrame(BlockFrame frame) {
262        Args.nullNotPermitted(frame, "frame");
263        this.frame = frame;
264    }
265
266    /**
267     * Returns the padding.
268     *
269     * @return The padding (never {@code null}).
270     *
271     * @see #setPadding(RectangleInsets)
272     */
273    public RectangleInsets getPadding() {
274        return this.padding;
275    }
276
277    /**
278     * Sets the padding (use {@link RectangleInsets#ZERO_INSETS} for no
279     * padding).
280     *
281     * @param padding  the padding ({@code null} not permitted).
282     *
283     * @see #getPadding()
284     */
285    public void setPadding(RectangleInsets padding) {
286        Args.nullNotPermitted(padding, "padding");
287        this.padding = padding;
288    }
289
290    /**
291     * Sets the padding.
292     *
293     * @param top  the top padding.
294     * @param left  the left padding.
295     * @param bottom  the bottom padding.
296     * @param right  the right padding.
297     */
298    public void setPadding(double top, double left, double bottom,
299                           double right) {
300        setPadding(new RectangleInsets(top, left, bottom, right));
301    }
302
303    /**
304     * Returns the x-offset for the content within the block.
305     *
306     * @return The x-offset.
307     *
308     * @see #getContentYOffset()
309     */
310    public double getContentXOffset() {
311        return this.margin.getLeft() + this.frame.getInsets().getLeft()
312            + this.padding.getLeft();
313    }
314
315    /**
316     * Returns the y-offset for the content within the block.
317     *
318     * @return The y-offset.
319     *
320     * @see #getContentXOffset()
321     */
322    public double getContentYOffset() {
323        return this.margin.getTop() + this.frame.getInsets().getTop()
324            + this.padding.getTop();
325    }
326
327    /**
328     * Arranges the contents of the block, with no constraints, and returns
329     * the block size.
330     *
331     * @param g2  the graphics device.
332     *
333     * @return The block size (in Java2D units, never {@code null}).
334     */
335    public Size2D arrange(Graphics2D g2) {
336        return arrange(g2, RectangleConstraint.NONE);
337    }
338
339    /**
340     * Arranges the contents of the block, within the given constraints, and
341     * returns the block size.
342     *
343     * @param g2  the graphics device.
344     * @param constraint  the constraint ({@code null} not permitted).
345     *
346     * @return The block size (in Java2D units, never {@code null}).
347     */
348    public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) {
349        Size2D base = new Size2D(getWidth(), getHeight());
350        return constraint.calculateConstrainedSize(base);
351    }
352
353    /**
354     * Returns the current bounds of the block.
355     *
356     * @return The bounds.
357     *
358     * @see #setBounds(Rectangle2D)
359     */
360    public Rectangle2D getBounds() {
361        return this.bounds;
362    }
363
364    /**
365     * Sets the bounds of the block.
366     *
367     * @param bounds  the bounds ({@code null} not permitted).
368     *
369     * @see #getBounds()
370     */
371    public void setBounds(Rectangle2D bounds) {
372        Args.nullNotPermitted(bounds, "bounds");
373        this.bounds = bounds;
374    }
375
376    /**
377     * Calculate the width available for content after subtracting
378     * the margin, border and padding space from the specified fixed
379     * width.
380     *
381     * @param fixedWidth  the fixed width.
382     *
383     * @return The available space.
384     *
385     * @see #trimToContentHeight(double)
386     */
387    protected double trimToContentWidth(double fixedWidth) {
388        double result = this.margin.trimWidth(fixedWidth);
389        result = this.frame.getInsets().trimWidth(result);
390        result = this.padding.trimWidth(result);
391        return Math.max(result, 0.0);
392    }
393
394    /**
395     * Calculate the height available for content after subtracting
396     * the margin, border and padding space from the specified fixed
397     * height.
398     *
399     * @param fixedHeight  the fixed height.
400     *
401     * @return The available space.
402     *
403     * @see #trimToContentWidth(double)
404     */
405    protected double trimToContentHeight(double fixedHeight) {
406        double result = this.margin.trimHeight(fixedHeight);
407        result = this.frame.getInsets().trimHeight(result);
408        result = this.padding.trimHeight(result);
409        return Math.max(result, 0.0);
410    }
411
412    /**
413     * Returns a constraint for the content of this block that will result in
414     * the bounds of the block matching the specified constraint.
415     *
416     * @param c  the outer constraint ({@code null} not permitted).
417     *
418     * @return The content constraint.
419     */
420    protected RectangleConstraint toContentConstraint(RectangleConstraint c) {
421        Args.nullNotPermitted(c, "c");
422        if (c.equals(RectangleConstraint.NONE)) {
423            return c;
424        }
425        double w = c.getWidth();
426        Range wr = c.getWidthRange();
427        double h = c.getHeight();
428        Range hr = c.getHeightRange();
429        double ww = trimToContentWidth(w);
430        double hh = trimToContentHeight(h);
431        Range wwr = trimToContentWidth(wr);
432        Range hhr = trimToContentHeight(hr);
433        return new RectangleConstraint(ww, wwr, c.getWidthConstraintType(),
434            hh, hhr, c.getHeightConstraintType());
435    }
436
437    private Range trimToContentWidth(Range r) {
438        if (r == null) {
439            return null;
440        }
441        double lowerBound = 0.0;
442        double upperBound = Double.POSITIVE_INFINITY;
443        if (r.getLowerBound() > 0.0) {
444            lowerBound = trimToContentWidth(r.getLowerBound());
445        }
446        if (r.getUpperBound() < Double.POSITIVE_INFINITY) {
447            upperBound = trimToContentWidth(r.getUpperBound());
448        }
449        return new Range(lowerBound, upperBound);
450    }
451
452    private Range trimToContentHeight(Range r) {
453        if (r == null) {
454            return null;
455        }
456        double lowerBound = 0.0;
457        double upperBound = Double.POSITIVE_INFINITY;
458        if (r.getLowerBound() > 0.0) {
459            lowerBound = trimToContentHeight(r.getLowerBound());
460        }
461        if (r.getUpperBound() < Double.POSITIVE_INFINITY) {
462            upperBound = trimToContentHeight(r.getUpperBound());
463        }
464        return new Range(lowerBound, upperBound);
465    }
466
467    /**
468     * Adds the margin, border and padding to the specified content width.
469     *
470     * @param contentWidth  the content width.
471     *
472     * @return The adjusted width.
473     */
474    protected double calculateTotalWidth(double contentWidth) {
475        double result = contentWidth;
476        result = this.padding.extendWidth(result);
477        result = this.frame.getInsets().extendWidth(result);
478        result = this.margin.extendWidth(result);
479        return result;
480    }
481
482    /**
483     * Adds the margin, border and padding to the specified content height.
484     *
485     * @param contentHeight  the content height.
486     *
487     * @return The adjusted height.
488     */
489    protected double calculateTotalHeight(double contentHeight) {
490        double result = contentHeight;
491        result = this.padding.extendHeight(result);
492        result = this.frame.getInsets().extendHeight(result);
493        result = this.margin.extendHeight(result);
494        return result;
495    }
496
497    /**
498     * Reduces the specified area by the amount of space consumed
499     * by the margin.
500     *
501     * @param area  the area ({@code null} not permitted).
502     *
503     * @return The trimmed area.
504     */
505    protected Rectangle2D trimMargin(Rectangle2D area) {
506        // defer argument checking...
507        this.margin.trim(area);
508        return area;
509    }
510
511    /**
512     * Reduces the specified area by the amount of space consumed
513     * by the border.
514     *
515     * @param area  the area ({@code null} not permitted).
516     *
517     * @return The trimmed area.
518     */
519    protected Rectangle2D trimBorder(Rectangle2D area) {
520        // defer argument checking...
521        this.frame.getInsets().trim(area);
522        return area;
523    }
524
525    /**
526     * Reduces the specified area by the amount of space consumed
527     * by the padding.
528     *
529     * @param area  the area ({@code null} not permitted).
530     *
531     * @return The trimmed area.
532     */
533    protected Rectangle2D trimPadding(Rectangle2D area) {
534        // defer argument checking...
535        this.padding.trim(area);
536        return area;
537    }
538
539    /**
540     * Draws the border around the perimeter of the specified area.
541     *
542     * @param g2  the graphics device.
543     * @param area  the area.
544     */
545    protected void drawBorder(Graphics2D g2, Rectangle2D area) {
546        this.frame.draw(g2, area);
547    }
548
549    /**
550     * Tests this block for equality with an arbitrary object.
551     *
552     * @param obj  the object ({@code null} permitted).
553     *
554     * @return A boolean.
555     */
556    @Override
557    public boolean equals(Object obj) {
558        if (obj == this) {
559            return true;
560        }
561        if (!(obj instanceof AbstractBlock)) {
562            return false;
563        }
564        AbstractBlock that = (AbstractBlock) obj;
565        if (!ObjectUtils.equal(this.id, that.id)) {
566            return false;
567        }
568        if (!this.frame.equals(that.frame)) {
569            return false;
570        }
571        if (!this.bounds.equals(that.bounds)) {
572            return false;
573        }
574        if (!this.margin.equals(that.margin)) {
575            return false;
576        }
577        if (!this.padding.equals(that.padding)) {
578            return false;
579        }
580        if (this.height != that.height) {
581            return false;
582        }
583        if (this.width != that.width) {
584            return false;
585        }
586        return true;
587    }
588
589    /**
590     * Returns a clone of this block.
591     *
592     * @return A clone.
593     *
594     * @throws CloneNotSupportedException if there is a problem creating the
595     *         clone.
596     */
597    @Override
598    public Object clone() throws CloneNotSupportedException {
599        AbstractBlock clone = (AbstractBlock) super.clone();
600        clone.bounds = (Rectangle2D) ShapeUtils.clone(this.bounds);
601        if (this.frame instanceof PublicCloneable) {
602            PublicCloneable pc = (PublicCloneable) this.frame;
603            clone.frame = (BlockFrame) pc.clone();
604        }
605        return clone;
606    }
607
608    /**
609     * Provides serialization support.
610     *
611     * @param stream  the output stream.
612     *
613     * @throws IOException if there is an I/O error.
614     */
615    private void writeObject(ObjectOutputStream stream) throws IOException {
616        stream.defaultWriteObject();
617        SerialUtils.writeShape(this.bounds, stream);
618    }
619
620    /**
621     * Provides serialization support.
622     *
623     * @param stream  the input stream.
624     *
625     * @throws IOException  if there is an I/O error.
626     * @throws ClassNotFoundException  if there is a classpath problem.
627     */
628    private void readObject(ObjectInputStream stream)
629        throws IOException, ClassNotFoundException {
630        stream.defaultReadObject();
631        this.bounds = (Rectangle2D) SerialUtils.readShape(stream);
632    }
633
634}