1 /*
   2  * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javafx.scene.layout;
  27 
  28 import java.util.ArrayList;
  29 import java.util.Collections;
  30 import java.util.List;
  31 import javafx.beans.property.ObjectProperty;
  32 import javafx.css.CssMetaData;
  33 import javafx.css.StyleableObjectProperty;
  34 import javafx.css.StyleableProperty;
  35 import javafx.geometry.Insets;
  36 import javafx.geometry.Orientation;
  37 import javafx.geometry.Pos;
  38 import javafx.geometry.VPos;
  39 import javafx.scene.Node;
  40 import com.sun.javafx.css.converters.EnumConverter;
  41 import java.util.function.Function;
  42 import javafx.css.Styleable;
  43 import javafx.geometry.HPos;
  44 import javafx.util.Callback;
  45 
  46 /**
  47  *
  48  * StackPane lays out its children in a back-to-front stack.
  49  * <p>
  50  * The z-order of the children is defined by the order of the children list
  51  * with the 0th child being the bottom and last child on top.  If a border and/or
  52  * padding have been set, the children will be layed out within those insets.
  53  * <p>
  54  * The stackpane will attempt to resize each child to fill its content area.
  55  * If the child could not be sized to fill the stackpane (either because it was
  56  * not resizable or its max size prevented it) then it will be aligned within
  57  * the area using the alignment property, which defaults to Pos.CENTER.
  58  * <p>
  59  * StackPane example:
  60  * <pre><code>     StackPane stack = new StackPane();
  61  *     stack.getChildren().addAll(new Rectangle(100,100,Color.BLUE), new Label("Go!));
  62  * </code></pre>
  63  * <p>
  64  * StackPane lays out each managed child regardless of the child's
  65  * visible property value; unmanaged children are ignored.</p>
  66  * <p>
  67  * StackPane may be styled with backgrounds and borders using CSS.  See
  68  * {@link javafx.scene.layout.Region Region} for details.</p>
  69  *
  70  * <h4>Resizable Range</h4>
  71  *
  72  * A stackpane's parent will resize the stackpane within the stackpane's resizable range
  73  * during layout.   By default the stackpane computes this range based on its content
  74  * as outlined in the table below.
  75  * <p>
  76  * <table border="1">
  77  * <tr><td></td><th>width</th><th>height</th></tr>
  78  * <tr><th>minimum</th>
  79  * <td>left/right insets plus the largest of the children's min widths.</td>
  80  * <td>top/bottom insets plus the largest of the children's min heights.</td></tr>
  81  * <tr><th>preferred</th>
  82  * <td>left/right insets plus the largest of the children's pref widths.</td>
  83  * <td>top/bottom insets plus the largest of the children's pref heights.</td></tr>
  84  * <tr><th>maximum</th>
  85  * <td>Double.MAX_VALUE</td><td>Double.MAX_VALUE</td></tr>
  86  * </table>
  87  * <p>
  88  * A stackpane's unbounded maximum width and height are an indication to the parent that
  89  * it may be resized beyond its preferred size to fill whatever space is assigned
  90  * to it.
  91  * <p>
  92  * StackPane provides properties for setting the size range directly.  These
  93  * properties default to the sentinel value USE_COMPUTED_SIZE, however the
  94  * application may set them to other values as needed:
  95  * <pre><code>     // ensure stackpane is never resized beyond it's preferred size
  96  *     <b>stackpane.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);</b>
  97  * </code></pre>
  98  * Applications may restore the computed values by setting these properties back
  99  * to USE_COMPUTED_SIZE.
 100  *
 101  * <p>
 102  * StackPane does not clip its content by default, so it is possible that childrens'
 103  * bounds may extend outside its own bounds if a child's min size prevents it from
 104  * being fit within the stackpane.</p>
 105  *
 106  * <h4>Optional Layout Constraints</h4>
 107  *
 108  * An application may set constraints on individual children to customize StackPane's layout.
 109  * For each constraint, StackPane provides a static method for setting it on the child.
 110  * <p>
 111  * <table border="1">
 112  * <tr><th>Constraint</th><th>Type</th><th>Description</th></tr>
 113  * <tr><td>alignment</td><td>javafx.geometry.Pos</td><td>The alignment of the child within the stackpane.</td></tr>
 114  * <tr><td>margin</td><td>javafx.geometry.Insets</td><td>Margin space around the outside of the child.</td></tr>
 115  * </table>
 116  * <p>
 117  * Examples:
 118  * <pre><code>     // Align the title Label at the bottom-center of the stackpane
 119  *     Label title = new Label();
 120  *     <b>StackPane.setAlignment(title, Pos.BOTTOM_CENTER);</b>
 121  *     stackpane.getChildren.addAll(new ImageView(...), title);
 122  *
 123  *     // Create an 8 pixel margin around a listview in the stackpane
 124  *     ListView list = new ListView();
 125  *     <b>StackPane.setMargin(list, new Insets(8,8,8,8);</b>
 126  *     stackpane.getChildren().add(list);
 127  * </code></pre>
 128  *
 129  * @since JavaFX 2.0
 130  */
 131 
 132 public class StackPane extends Pane {
 133 
 134     private boolean biasDirty = true;
 135     private boolean performingLayout = false;
 136     private Orientation bias;
 137 
 138     /********************************************************************
 139      *  BEGIN static methods
 140      ********************************************************************/
 141 
 142     private static final String MARGIN_CONSTRAINT = "stackpane-margin";
 143     private static final String ALIGNMENT_CONSTRAINT = "stackpane-alignment";
 144 
 145    /**
 146      * Sets the alignment for the child when contained by a stackpane.
 147      * If set, will override the stackpane's default alignment.
 148      * Setting the value to null will remove the constraint.
 149      * @param child the child node of a stackpane
 150      * @param value the alignment position for the child
 151      */
 152     public static void setAlignment(Node child, Pos value) {
 153         setConstraint(child, ALIGNMENT_CONSTRAINT, value);
 154     }
 155 
 156     /**
 157      * Returns the child's alignment constraint if set.
 158      * @param child the child node of a stackpane
 159      * @return the alignment position for the child or null if no alignment was set
 160      */
 161     public static Pos getAlignment(Node child) {
 162         return (Pos)getConstraint(child, ALIGNMENT_CONSTRAINT);
 163     }
 164 
 165     /**
 166      * Sets the margin for the child when contained by a stackpane.
 167      * If set, the stackpane will layout the child with the margin space around it.
 168      * Setting the value to null will remove the constraint.
 169      * @param child the child node of a stackpane
 170      * @param value the margin of space around the child
 171      */
 172     public static void setMargin(Node child, Insets value) {
 173         setConstraint(child, MARGIN_CONSTRAINT, value);
 174     }
 175 
 176     /**
 177      * Returns the child's margin constraints if set.
 178      * @param child the child node of a stackpane
 179      * @return the margin for the child or null if no margin was set
 180      */
 181     public static Insets getMargin(Node child) {
 182         return (Insets)getConstraint(child, MARGIN_CONSTRAINT);
 183     }
 184 
 185     private static final Callback<Node, Insets> marginAccessor = n -> getMargin(n);
 186 
 187     /**
 188      * Removes all stackpane constraints from the child node.
 189      * @param child the child node
 190      */
 191     public static void clearConstraints(Node child) {
 192         setAlignment(child, null);
 193         setMargin(child, null);
 194     }
 195     /********************************************************************
 196      *  END static methods
 197      ********************************************************************/
 198 
 199     /**
 200      * Creates a StackPane layout with default CENTER alignment.
 201      */
 202     public StackPane() {
 203         super();
 204     }
 205 
 206     /**
 207      * Creates a StackPane layout with default CENTER alignment.
 208      * @param children The initial set of children for this pane.
 209      * @since JavaFX 8.0
 210      */
 211     public StackPane(Node... children) {
 212         super();
 213         getChildren().addAll(children);
 214     }
 215 
 216     /**
 217      * The default alignment of children within the stackpane's width and height.
 218      * This may be overridden on individual children by setting the child's
 219      * alignment constraint.
 220      */
 221     public final ObjectProperty<Pos> alignmentProperty() {
 222         if (alignment == null) {
 223             alignment = new StyleableObjectProperty<Pos>(Pos.CENTER) {
 224                 @Override
 225                 public void invalidated() {
 226                     requestLayout();
 227                 }
 228 
 229                 @Override
 230                 public CssMetaData<StackPane, Pos> getCssMetaData() {
 231                     return StyleableProperties.ALIGNMENT;
 232                 }
 233 
 234                 @Override
 235                 public Object getBean() {
 236                     return StackPane.this;
 237                 }
 238 
 239                 @Override
 240                 public String getName() {
 241                     return "alignment";
 242                 }
 243             };
 244         }
 245         return alignment;
 246     }
 247 
 248     private ObjectProperty<Pos> alignment;
 249     public final void setAlignment(Pos value) { alignmentProperty().set(value); }
 250     public final Pos getAlignment() { return alignment == null ? Pos.CENTER : alignment.get(); }
 251     private Pos getAlignmentInternal() {
 252         Pos localPos = getAlignment();
 253         return localPos == null ? Pos.CENTER : localPos;
 254     }
 255 
 256     /**
 257      *
 258      * @return the first non-null contentBias of its managed children or null if no managed children
 259      * have a content bias.
 260      */
 261     @Override public Orientation getContentBias() {
 262         if (biasDirty) {
 263             bias = null;
 264             final List<Node> children = getManagedChildren();
 265             for (Node child : children) {
 266                 Orientation contentBias = child.getContentBias();
 267                 if (contentBias != null) {
 268                     bias = contentBias;
 269                     if (contentBias == Orientation.HORIZONTAL) {
 270                         break;
 271                     }
 272                 }
 273             }
 274             biasDirty = false;
 275         }
 276         return bias;
 277     }
 278 
 279     @Override protected double computeMinWidth(double height) {
 280         List<Node>managed = getManagedChildren();
 281         return getInsets().getLeft() +
 282                computeMaxMinAreaWidth(managed, marginAccessor, height, true) +
 283                getInsets().getRight();
 284     }
 285 
 286     @Override protected double computeMinHeight(double width) {
 287         List<Node>managed = getManagedChildren();
 288         return getInsets().getTop() +
 289                computeMaxMinAreaHeight(managed, marginAccessor, getAlignmentInternal().getVpos(), width) +
 290                getInsets().getBottom();
 291     }
 292 
 293     @Override protected double computePrefWidth(double height) {
 294         List<Node>managed = getManagedChildren();
 295         Insets padding = getInsets();
 296         return padding.getLeft() +
 297                computeMaxPrefAreaWidth(managed, marginAccessor,
 298                                        (height == -1) ? -1 : (height - padding.getTop() - padding.getBottom()), true) +
 299                padding.getRight();
 300     }
 301 
 302     @Override protected double computePrefHeight(double width) {
 303         List<Node>managed = getManagedChildren();
 304         Insets padding = getInsets();
 305         return padding.getTop() +
 306                computeMaxPrefAreaHeight(managed, marginAccessor,
 307                                         (width == -1) ? -1 : (width - padding.getLeft() - padding.getRight()),
 308                                         getAlignmentInternal().getVpos()) +
 309                padding.getBottom();
 310     }
 311 
 312 
 313     @Override public void requestLayout() {
 314         if (performingLayout) {
 315             return;
 316         }
 317         biasDirty = true;
 318         bias = null;
 319         super.requestLayout();
 320     }
 321 
 322     @Override protected void layoutChildren() {
 323         performingLayout = true;
 324         List<Node> managed = getManagedChildren();
 325         Pos align = getAlignmentInternal();
 326         HPos alignHpos = align.getHpos();
 327         VPos alignVpos = align.getVpos();
 328         final double width = getWidth();
 329         double height = getHeight();
 330         double top = getInsets().getTop();
 331         double right = getInsets().getRight();
 332         double left = getInsets().getLeft();
 333         double bottom = getInsets().getBottom();
 334         double contentWidth = width - left - right;
 335         double contentHeight = height - top - bottom;
 336         double baselineOffset = alignVpos == VPos.BASELINE ?
 337                 getAreaBaselineOffset(managed, marginAccessor, i -> width, contentHeight, true)
 338                                     : 0;
 339         for (int i = 0, size = managed.size(); i < size; i++) {
 340             Node child = managed.get(i);
 341             Pos childAlignment = StackPane.getAlignment(child);
 342             layoutInArea(child, left, top,
 343                            contentWidth, contentHeight,
 344                            baselineOffset, getMargin(child),
 345                            childAlignment != null? childAlignment.getHpos() : alignHpos,
 346                            childAlignment != null? childAlignment.getVpos() : alignVpos);
 347         }
 348         performingLayout = false;
 349     }
 350 
 351     /***************************************************************************
 352      *                                                                         *
 353      *                         Stylesheet Handling                             *
 354      *                                                                         *
 355      **************************************************************************/
 356 
 357      /**
 358       * Super-lazy instantiation pattern from Bill Pugh.
 359       * @treatAsPrivate implementation detail
 360       */
 361      private static class StyleableProperties {
 362          private static final CssMetaData<StackPane,Pos> ALIGNMENT =
 363              new CssMetaData<StackPane,Pos>("-fx-alignment",
 364                  new EnumConverter<Pos>(Pos.class),
 365                  Pos.CENTER) {
 366 
 367             @Override
 368             public boolean isSettable(StackPane node) {
 369                 return node.alignment == null ||
 370                         !node.alignment.isBound();
 371             }
 372 
 373             @Override
 374             public StyleableProperty<Pos> getStyleableProperty(StackPane node) {
 375                 return (StyleableProperty<Pos>)node.alignmentProperty();
 376             }
 377         };
 378 
 379          private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES;
 380          static {
 381             final List<CssMetaData<? extends Styleable, ?>> styleables =
 382                 new ArrayList<CssMetaData<? extends Styleable, ?>>(Region.getClassCssMetaData());
 383             styleables.add(ALIGNMENT);
 384             STYLEABLES = Collections.unmodifiableList(styleables);
 385          }
 386     }
 387 
 388     /**
 389      * @return The CssMetaData associated with this class, which may include the
 390      * CssMetaData of its super classes.
 391      * @since JavaFX 8.0
 392      */
 393     public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() {
 394         return StyleableProperties.STYLEABLES;
 395     }
 396 
 397     /**
 398      * {@inheritDoc}
 399      *
 400      * @since JavaFX 8.0
 401      */
 402 
 403 
 404     @Override
 405     public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() {
 406         return getClassCssMetaData();
 407     }
 408 
 409 }