1 /*
   2  * Copyright (c) 2010, 2016, 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.control;
  27 
  28 import java.util.ArrayList;
  29 import java.util.Collections;
  30 import java.util.List;
  31 import java.util.WeakHashMap;
  32 
  33 import javafx.beans.DefaultProperty;
  34 import javafx.beans.property.DoubleProperty;
  35 import javafx.beans.property.ObjectProperty;
  36 import javafx.beans.property.SimpleDoubleProperty;
  37 import javafx.beans.value.WritableValue;
  38 import javafx.collections.FXCollections;
  39 import javafx.collections.ListChangeListener;
  40 import javafx.collections.ObservableList;
  41 import javafx.geometry.Orientation;
  42 import javafx.scene.Node;
  43 
  44 import javafx.css.StyleableObjectProperty;
  45 import javafx.css.CssMetaData;
  46 import javafx.css.PseudoClass;
  47 
  48 import javafx.css.converter.EnumConverter;
  49 import javafx.scene.control.skin.SplitPaneSkin;
  50 
  51 import javafx.css.Styleable;
  52 import javafx.css.StyleableProperty;
  53 
  54 /**
  55  * <p>A control that has two or more sides, each separated by a divider, which can be
  56  * dragged by the user to give more space to one of the sides, resulting in
  57  * the other side shrinking by an equal amount.</p>
  58  *
  59  * <p>{@link Node Nodes} can be positioned horizontally next to each other, or stacked
  60  * vertically. This can be controlled by setting the {@link #orientationProperty()}.</p>
  61  *
  62  * <p> The dividers in a SplitPane have the following behavior
  63  * <ul>
  64  * <li>Dividers cannot overlap another divider</li>
  65  * <li>Dividers cannot overlap a node.</li>
  66  * <li>Dividers moving to the left/top will stop when the node's min size is reached.</li>
  67  * <li>Dividers moving to the right/bottom will stop when the node's max size is reached.</li>
  68  * </ul>
  69  *
  70  * <p>Nodes needs to be placed inside a layout container before they are added
  71  * into the SplitPane.  If the node is not inside a layout container
  72  * the maximum and minimum position of the divider will be the
  73  * maximum and minimum size of the content.
  74  * </p>
  75  *
  76  * <p>A divider's position ranges from 0 to 1.0(inclusive).  A position of 0 will place the
  77  * divider at the left/top most edge of the SplitPane plus the minimum size of the node.  A
  78  * position of 1.0 will place the divider at the right/bottom most edge of the SplitPane minus the
  79  * minimum size of the node.  A divider position of 0.5 will place the
  80  * the divider in the middle of the SplitPane.  Setting the divider position greater
  81  * than the node's maximum size position will result in the divider being set at the
  82  * node's maximum size position.  Setting the divider position less than the node's minimum size position
  83  * will result in the divider being set at the node's minimum size position. Therefore the value set in
  84  * {@link #setDividerPosition} and {@link #setDividerPositions} may not be the same as the value returned by
  85  * {@link #getDividerPositions}.
  86  * </p>
  87  *
  88  * <p>If there are more than two nodes in the SplitPane and the divider positions are set in such a
  89  * way that the dividers cannot fit the nodes the dividers will be automatically adjusted by the SplitPane.
  90  * <p>For example we have three nodes whose sizes and divider positions are
  91  * </p>
  92  * <pre>
  93  * Node 1: min 25 max 100
  94  * Node 2: min 100 max 200
  95  * Node 3: min 25 max 50
  96  * divider 1: 0.40
  97  * divider 2: 0.45
  98  * </pre>
  99  *
 100  * <p>The result will be Node 1 size will be its pref size and divider 1 will be positioned 0.40,
 101  * Node 2 size will be its min size and divider 2 position will be the min size of Node 2 plus
 102  * divider 1 position, and the remaining space will be given to Node 3.
 103  * </p>
 104  *
 105  * <p>
 106  * SplitPane sets focusTraversable to false.
 107  * </p>
 108  *
 109  * <p>Example:</p>
 110  * <pre><code>
 111  * SplitPane sp = new SplitPane();
 112  * final StackPane sp1 = new StackPane();
 113  * sp1.getItems().add(new Button("Button One"));
 114  * final StackPane sp2 = new StackPane();
 115  * sp2.getItems().add(new Button("Button Two"));
 116  * final StackPane sp3 = new StackPane();
 117  * sp3.getItems().add(new Button("Button Three"));
 118  * sp.getItems().addAll(sp1, sp2, sp3);
 119  * sp.setDividerPositions(0.3f, 0.6f, 0.9f);
 120  * </code></pre>
 121  *
 122  * @since JavaFX 2.0
 123  */
 124 @DefaultProperty("items")
 125 public class SplitPane extends Control {
 126 
 127     /********************************************************************
 128      *  static methods
 129      ********************************************************************/
 130     private static final String RESIZABLE_WITH_PARENT = "resizable-with-parent";
 131 
 132     /**
 133      * Sets a node in the SplitPane to be resizable or not when the SplitPane is
 134      * resized.  By default all node are resizable.  Setting value to false will
 135      * prevent the node from being resized.
 136      * @param node A node in the SplitPane.
 137      * @param value true if the node is resizable or false if not resizable.
 138      * @since JavaFX 2.1
 139      */
 140     public static void setResizableWithParent(Node node, Boolean value) {
 141         if (value == null) {
 142             node.getProperties().remove(RESIZABLE_WITH_PARENT);
 143         } else {
 144             node.getProperties().put(RESIZABLE_WITH_PARENT, value);
 145         }
 146     }
 147 
 148     /**
 149      * Return true if the node is resizable when the parent container is resized false otherwise.
 150      * @param node A node in the SplitPane.
 151      * @defaultValue true
 152      * @return true if the node is resizable false otherwise.
 153      * @since JavaFX 2.1
 154      */
 155     public static Boolean isResizableWithParent(Node node) {
 156         if (node.hasProperties()) {
 157             Object value = node.getProperties().get(RESIZABLE_WITH_PARENT);
 158             if (value != null) {
 159                 return (Boolean)value;
 160             }
 161         }
 162         return true;
 163     }
 164 
 165     /***************************************************************************
 166      *                                                                         *
 167      * Constructors                                                            *
 168      *                                                                         *
 169      **************************************************************************/
 170 
 171     /**
 172      * Creates a new SplitPane with no content.
 173      */
 174     public SplitPane() {
 175         this((Node[])null);
 176     }
 177 
 178     /**
 179      * Creates a new SplitPane with the given items set as the content to split
 180      * between one or more dividers.
 181      *
 182      * @param items The items to place inside the SplitPane.
 183      * @since JavaFX 8u40
 184      */
 185     public SplitPane(Node... items) {
 186         getStyleClass().setAll(DEFAULT_STYLE_CLASS);
 187         // focusTraversable is styleable through css. Calling setFocusTraversable
 188         // makes it look to css like the user set the value and css will not
 189         // override. Initializing focusTraversable by calling applyStyle with a
 190         // null StyleOrigin ensures that css will be able to override the value.
 191         ((StyleableProperty<Boolean>)(WritableValue<Boolean>)focusTraversableProperty()).applyStyle(null, Boolean.FALSE);
 192 
 193         getItems().addListener(new ListChangeListener<Node>() {
 194             @Override public void onChanged(Change<? extends Node> c) {
 195                 while (c.next()) {
 196                     int from = c.getFrom();
 197                     int index = from;
 198                     for (int i = 0; i < c.getRemovedSize(); i++) {
 199                         if (index < dividers.size()) {
 200                             dividerCache.put(index, Double.MAX_VALUE);
 201                         } else if (index == dividers.size()) {
 202                             if (!dividers.isEmpty()) {
 203                                 if (c.wasReplaced()) {
 204                                     dividerCache.put(index - 1, dividers.get(index - 1).getPosition());
 205                                 } else {
 206                                     dividerCache.put(index - 1, Double.MAX_VALUE);
 207                                 }
 208                             }
 209                         }
 210                         index++;
 211                     }
 212                     for (int i = 0; i < dividers.size(); i++) {
 213                         if (dividerCache.get(i) == null) {
 214                             dividerCache.put(i, dividers.get(i).getPosition());
 215                         }
 216                     }
 217                 }
 218                 dividers.clear();
 219                 for (int i = 0; i < getItems().size() - 1; i++) {
 220                     if (dividerCache.containsKey(i) && dividerCache.get(i) != Double.MAX_VALUE) {
 221                         Divider d = new Divider();
 222                         d.setPosition(dividerCache.get(i));
 223                         dividers.add(d);
 224                     } else {
 225                         dividers.add(new Divider());
 226                     }
 227                     dividerCache.remove(i);
 228                 }
 229             }
 230         });
 231 
 232         if (items != null) {
 233             getItems().addAll(items);
 234         }
 235 
 236         // initialize pseudo-class state
 237         pseudoClassStateChanged(HORIZONTAL_PSEUDOCLASS_STATE, true);
 238     }
 239 
 240     /***************************************************************************
 241      *                                                                         *
 242      * Properties                                                              *
 243      *                                                                         *
 244      **************************************************************************/
 245 
 246     // --- Vertical
 247     private ObjectProperty<Orientation> orientation;
 248 
 249     /**
 250      * <p>This property controls how the SplitPane should be displayed to the
 251      * user. {@link javafx.geometry.Orientation#HORIZONTAL} will result in
 252      * two (or more) nodes being placed next to each other horizontally, whilst
 253      * {@link javafx.geometry.Orientation#VERTICAL} will result in the nodes being
 254      * stacked vertically.</p>
 255      *
 256      */
 257     public final void setOrientation(Orientation value) {
 258         orientationProperty().set(value);
 259     };
 260 
 261     /**
 262      * The orientation for the SplitPane.
 263      * @return The orientation for the SplitPane.
 264      */
 265     public final Orientation getOrientation() {
 266         return orientation == null ? Orientation.HORIZONTAL : orientation.get();
 267     }
 268 
 269     /**
 270      * The orientation for the SplitPane.
 271      */
 272     public final ObjectProperty<Orientation> orientationProperty() {
 273         if (orientation == null) {
 274             orientation = new StyleableObjectProperty<Orientation>(Orientation.HORIZONTAL) {
 275                 @Override public void invalidated() {
 276                     final boolean isVertical = (get() == Orientation.VERTICAL);
 277                     pseudoClassStateChanged(VERTICAL_PSEUDOCLASS_STATE,    isVertical);
 278                     pseudoClassStateChanged(HORIZONTAL_PSEUDOCLASS_STATE, !isVertical);
 279                 }
 280 
 281                 @Override public CssMetaData<SplitPane,Orientation> getCssMetaData() {
 282                     return StyleableProperties.ORIENTATION;
 283                 }
 284 
 285                 @Override
 286                 public Object getBean() {
 287                     return SplitPane.this;
 288                 }
 289 
 290                 @Override
 291                 public String getName() {
 292                     return "orientation";
 293                 }
 294             };
 295         }
 296         return orientation;
 297     }
 298 
 299 
 300 
 301     /***************************************************************************
 302      *                                                                         *
 303      * Instance Variables                                                      *
 304      *                                                                         *
 305      **************************************************************************/
 306 
 307     private final ObservableList<Node> items = FXCollections.observableArrayList();
 308 
 309     private final ObservableList<Divider> dividers = FXCollections.observableArrayList();
 310     private final ObservableList<Divider> unmodifiableDividers = FXCollections.unmodifiableObservableList(dividers);
 311 
 312     // Cache the divider positions if the items have not been created.
 313     private final WeakHashMap<Integer, Double> dividerCache = new WeakHashMap<Integer, Double>();
 314 
 315     /***************************************************************************
 316      *                                                                         *
 317      * Public API                                                              *
 318      *                                                                         *
 319      **************************************************************************/
 320 
 321     /**
 322      * Returns an ObservableList which can be use to modify the contents of the SplitPane.
 323      * The order the nodes are placed into this list will be the same order in the SplitPane.
 324      *
 325      * @return the list of items in this SplitPane.
 326      */
 327     public ObservableList<Node> getItems() {
 328         return items;
 329     }
 330 
 331     /**
 332      * Returns an unmodifiable list of all the dividers in this SplitPane.
 333      *
 334      * @return the list of dividers.
 335      */
 336     public ObservableList<Divider> getDividers() {
 337         return unmodifiableDividers;
 338     }
 339 
 340     /**
 341      * Sets the position of the divider at the specified divider index.
 342      *
 343      * @param dividerIndex the index of the divider.
 344      * @param position the divider position, between 0.0 and 1.0 (inclusive).
 345      */
 346     public void setDividerPosition(int dividerIndex, double position) {
 347         if (getDividers().size() <= dividerIndex)  {
 348             dividerCache.put(dividerIndex, position);
 349             return;
 350         }
 351         if (dividerIndex >= 0) {
 352             getDividers().get(dividerIndex).setPosition(position);
 353         }
 354     }
 355 
 356     /**
 357      * Sets the position of the divider
 358      *
 359      * @param positions the divider position, between 0.0 and 1.0 (inclusive).
 360      */
 361     public void setDividerPositions(double... positions) {
 362         if (dividers.isEmpty()) {
 363             for (int i = 0; i < positions.length; i++) {
 364                 dividerCache.put(i, positions[i]);
 365             }
 366             return;
 367         }
 368         for (int i = 0; i < positions.length && i < dividers.size(); i++) {
 369             dividers.get(i).setPosition(positions[i]);
 370         }
 371     }
 372 
 373     /**
 374      * Returns an array of double containing the position of each divider.
 375      *
 376      * @return an array of double containing the position of each divider.
 377      */
 378     public double[] getDividerPositions() {
 379         double[] positions = new double[dividers.size()];
 380         for (int i = 0; i < dividers.size(); i++) {
 381             positions[i] = dividers.get(i).getPosition();
 382         }
 383         return positions;
 384     }
 385 
 386     /** {@inheritDoc} */
 387     @Override protected Skin<?> createDefaultSkin() {
 388         return new SplitPaneSkin(this);
 389     }
 390 
 391     /***************************************************************************
 392      *                                                                         *
 393      *                         Stylesheet Handling                             *
 394      *                                                                         *
 395      **************************************************************************/
 396 
 397     private static final String DEFAULT_STYLE_CLASS = "split-pane";
 398 
 399     private static class StyleableProperties {
 400         private static final CssMetaData<SplitPane,Orientation> ORIENTATION =
 401             new CssMetaData<SplitPane,Orientation>("-fx-orientation",
 402                 new EnumConverter<Orientation>(Orientation.class),
 403                 Orientation.HORIZONTAL) {
 404 
 405             @Override
 406             public Orientation getInitialValue(SplitPane node) {
 407                 // A vertical SplitPane should remain vertical
 408                 return node.getOrientation();
 409             }
 410 
 411             @Override
 412             public boolean isSettable(SplitPane n) {
 413                 return n.orientation == null || !n.orientation.isBound();
 414             }
 415 
 416             @Override
 417             public StyleableProperty<Orientation> getStyleableProperty(SplitPane n) {
 418                 return (StyleableProperty<Orientation>)(WritableValue<Orientation>)n.orientationProperty();
 419             }
 420         };
 421 
 422         private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES;
 423         static {
 424             final List<CssMetaData<? extends Styleable, ?>> styleables =
 425                 new ArrayList<CssMetaData<? extends Styleable, ?>>(Control.getClassCssMetaData());
 426             styleables.add(ORIENTATION);
 427             STYLEABLES = Collections.unmodifiableList(styleables);
 428         }
 429     }
 430 
 431     /**
 432      * @return The CssMetaData associated with this class, which may include the
 433      * CssMetaData of its superclasses.
 434      * @since JavaFX 8.0
 435      */
 436     public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() {
 437         return StyleableProperties.STYLEABLES;
 438     }
 439 
 440     /**
 441      * {@inheritDoc}
 442      * @since JavaFX 8.0
 443      */
 444     @Override
 445     public List<CssMetaData<? extends Styleable, ?>> getControlCssMetaData() {
 446         return getClassCssMetaData();
 447     }
 448 
 449     private static final PseudoClass VERTICAL_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("vertical");
 450     private static final PseudoClass HORIZONTAL_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("horizontal");
 451 
 452     /**
 453      * Returns the initial focus traversable state of this control, for use
 454      * by the JavaFX CSS engine to correctly set its initial value. This method
 455      * is overridden as by default UI controls have focus traversable set to true,
 456      * but that is not appropriate for this control.
 457      *
 458      * @since 9
 459      */
 460     @Override protected Boolean getInitialFocusTraversable() {
 461         return Boolean.FALSE;
 462     }
 463 
 464 
 465     /***************************************************************************
 466      *                                                                         *
 467      * Support Classes                                                         *
 468      *                                                                         *
 469      **************************************************************************/
 470 
 471     /**
 472      * Represents a single divider in the SplitPane.
 473      * @since JavaFX 2.0
 474      */
 475     public static class Divider {
 476 
 477         /**
 478          * Creates a default Divider instance.
 479          */
 480         public Divider() {
 481 
 482         }
 483 
 484         /**
 485          * <p>Represents the location where the divider should ideally be
 486          * positioned, between 0.0 and 1.0 (inclusive). 0.0 represents the
 487          * left- or top-most point, and 1.0 represents the right- or bottom-most
 488          * point (depending on the horizontal property). The SplitPane will attempt
 489          * to get the divider to the point requested, but it must take into account
 490          * the minimum width/height of the nodes contained within it.</p>
 491          *
 492          * <p>As the user drags the SplitPane divider around this property will
 493          * be updated to always represent its current location.</p>
 494          *
 495          * @defaultValue 0.5
 496          */
 497         private DoubleProperty position;
 498         public final void setPosition(double value) {
 499             positionProperty().set(value);
 500         }
 501 
 502         public final double getPosition() {
 503             return position == null ? 0.5F : position.get();
 504         }
 505 
 506         public final DoubleProperty positionProperty() {
 507             if (position == null) {
 508                 position = new SimpleDoubleProperty(this, "position", 0.5F);// {
 509 //                    @Override protected void invalidated() {
 510 //                        if (get() < 0) {
 511 //                            this.value = value;
 512 //                        } else if (get() > 1) {
 513 //                            this.value = value;
 514 //                        }
 515 //                    }
 516 //                };
 517             }
 518             return position;
 519         }
 520     }
 521 }