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      * @param value the orientation value
 257      */
 258     public final void setOrientation(Orientation value) {
 259         orientationProperty().set(value);
 260     };
 261 
 262     /**
 263      * The orientation for the SplitPane.
 264      * @return The orientation for the SplitPane.
 265      */
 266     public final Orientation getOrientation() {
 267         return orientation == null ? Orientation.HORIZONTAL : orientation.get();
 268     }
 269 
 270     /**
 271      * The orientation for the SplitPane.
 272      * @return the orientation property for the SplitPane
 273      */
 274     public final ObjectProperty<Orientation> orientationProperty() {
 275         if (orientation == null) {
 276             orientation = new StyleableObjectProperty<Orientation>(Orientation.HORIZONTAL) {
 277                 @Override public void invalidated() {
 278                     final boolean isVertical = (get() == Orientation.VERTICAL);
 279                     pseudoClassStateChanged(VERTICAL_PSEUDOCLASS_STATE,    isVertical);
 280                     pseudoClassStateChanged(HORIZONTAL_PSEUDOCLASS_STATE, !isVertical);
 281                 }
 282 
 283                 @Override public CssMetaData<SplitPane,Orientation> getCssMetaData() {
 284                     return StyleableProperties.ORIENTATION;
 285                 }
 286 
 287                 @Override
 288                 public Object getBean() {
 289                     return SplitPane.this;
 290                 }
 291 
 292                 @Override
 293                 public String getName() {
 294                     return "orientation";
 295                 }
 296             };
 297         }
 298         return orientation;
 299     }
 300 
 301 
 302 
 303     /***************************************************************************
 304      *                                                                         *
 305      * Instance Variables                                                      *
 306      *                                                                         *
 307      **************************************************************************/
 308 
 309     private final ObservableList<Node> items = FXCollections.observableArrayList();
 310 
 311     private final ObservableList<Divider> dividers = FXCollections.observableArrayList();
 312     private final ObservableList<Divider> unmodifiableDividers = FXCollections.unmodifiableObservableList(dividers);
 313 
 314     // Cache the divider positions if the items have not been created.
 315     private final WeakHashMap<Integer, Double> dividerCache = new WeakHashMap<Integer, Double>();
 316 
 317     /***************************************************************************
 318      *                                                                         *
 319      * Public API                                                              *
 320      *                                                                         *
 321      **************************************************************************/
 322 
 323     /**
 324      * Returns an ObservableList which can be use to modify the contents of the SplitPane.
 325      * The order the nodes are placed into this list will be the same order in the SplitPane.
 326      *
 327      * @return the list of items in this SplitPane.
 328      */
 329     public ObservableList<Node> getItems() {
 330         return items;
 331     }
 332 
 333     /**
 334      * Returns an unmodifiable list of all the dividers in this SplitPane.
 335      *
 336      * @return the list of dividers.
 337      */
 338     public ObservableList<Divider> getDividers() {
 339         return unmodifiableDividers;
 340     }
 341 
 342     /**
 343      * Sets the position of the divider at the specified divider index.
 344      *
 345      * @param dividerIndex the index of the divider.
 346      * @param position the divider position, between 0.0 and 1.0 (inclusive).
 347      */
 348     public void setDividerPosition(int dividerIndex, double position) {
 349         if (getDividers().size() <= dividerIndex)  {
 350             dividerCache.put(dividerIndex, position);
 351             return;
 352         }
 353         if (dividerIndex >= 0) {
 354             getDividers().get(dividerIndex).setPosition(position);
 355         }
 356     }
 357 
 358     /**
 359      * Sets the position of the divider
 360      *
 361      * @param positions the divider position, between 0.0 and 1.0 (inclusive).
 362      */
 363     public void setDividerPositions(double... positions) {
 364         if (dividers.isEmpty()) {
 365             for (int i = 0; i < positions.length; i++) {
 366                 dividerCache.put(i, positions[i]);
 367             }
 368             return;
 369         }
 370         for (int i = 0; i < positions.length && i < dividers.size(); i++) {
 371             dividers.get(i).setPosition(positions[i]);
 372         }
 373     }
 374 
 375     /**
 376      * Returns an array of double containing the position of each divider.
 377      *
 378      * @return an array of double containing the position of each divider.
 379      */
 380     public double[] getDividerPositions() {
 381         double[] positions = new double[dividers.size()];
 382         for (int i = 0; i < dividers.size(); i++) {
 383             positions[i] = dividers.get(i).getPosition();
 384         }
 385         return positions;
 386     }
 387 
 388     /** {@inheritDoc} */
 389     @Override protected Skin<?> createDefaultSkin() {
 390         return new SplitPaneSkin(this);
 391     }
 392 
 393     /***************************************************************************
 394      *                                                                         *
 395      *                         Stylesheet Handling                             *
 396      *                                                                         *
 397      **************************************************************************/
 398 
 399     private static final String DEFAULT_STYLE_CLASS = "split-pane";
 400 
 401     private static class StyleableProperties {
 402         private static final CssMetaData<SplitPane,Orientation> ORIENTATION =
 403             new CssMetaData<SplitPane,Orientation>("-fx-orientation",
 404                 new EnumConverter<Orientation>(Orientation.class),
 405                 Orientation.HORIZONTAL) {
 406 
 407             @Override
 408             public Orientation getInitialValue(SplitPane node) {
 409                 // A vertical SplitPane should remain vertical
 410                 return node.getOrientation();
 411             }
 412 
 413             @Override
 414             public boolean isSettable(SplitPane n) {
 415                 return n.orientation == null || !n.orientation.isBound();
 416             }
 417 
 418             @Override
 419             public StyleableProperty<Orientation> getStyleableProperty(SplitPane n) {
 420                 return (StyleableProperty<Orientation>)(WritableValue<Orientation>)n.orientationProperty();
 421             }
 422         };
 423 
 424         private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES;
 425         static {
 426             final List<CssMetaData<? extends Styleable, ?>> styleables =
 427                 new ArrayList<CssMetaData<? extends Styleable, ?>>(Control.getClassCssMetaData());
 428             styleables.add(ORIENTATION);
 429             STYLEABLES = Collections.unmodifiableList(styleables);
 430         }
 431     }
 432 
 433     /**
 434      * @return The CssMetaData associated with this class, which may include the
 435      * CssMetaData of its superclasses.
 436      * @since JavaFX 8.0
 437      */
 438     public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() {
 439         return StyleableProperties.STYLEABLES;
 440     }
 441 
 442     /**
 443      * {@inheritDoc}
 444      * @since JavaFX 8.0
 445      */
 446     @Override
 447     public List<CssMetaData<? extends Styleable, ?>> getControlCssMetaData() {
 448         return getClassCssMetaData();
 449     }
 450 
 451     private static final PseudoClass VERTICAL_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("vertical");
 452     private static final PseudoClass HORIZONTAL_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("horizontal");
 453 
 454     /**
 455      * Returns the initial focus traversable state of this control, for use
 456      * by the JavaFX CSS engine to correctly set its initial value. This method
 457      * is overridden as by default UI controls have focus traversable set to true,
 458      * but that is not appropriate for this control.
 459      *
 460      * @since 9
 461      */
 462     @Override protected Boolean getInitialFocusTraversable() {
 463         return Boolean.FALSE;
 464     }
 465 
 466 
 467     /***************************************************************************
 468      *                                                                         *
 469      * Support Classes                                                         *
 470      *                                                                         *
 471      **************************************************************************/
 472 
 473     /**
 474      * Represents a single divider in the SplitPane.
 475      * @since JavaFX 2.0
 476      */
 477     public static class Divider {
 478 
 479         /**
 480          * Creates a default Divider instance.
 481          */
 482         public Divider() {
 483 
 484         }
 485 
 486         /**
 487          * <p>Represents the location where the divider should ideally be
 488          * positioned, between 0.0 and 1.0 (inclusive). 0.0 represents the
 489          * left- or top-most point, and 1.0 represents the right- or bottom-most
 490          * point (depending on the horizontal property). The SplitPane will attempt
 491          * to get the divider to the point requested, but it must take into account
 492          * the minimum width/height of the nodes contained within it.</p>
 493          *
 494          * <p>As the user drags the SplitPane divider around this property will
 495          * be updated to always represent its current location.</p>
 496          *
 497          * @defaultValue 0.5
 498          */
 499         private DoubleProperty position;
 500         public final void setPosition(double value) {
 501             positionProperty().set(value);
 502         }
 503 
 504         public final double getPosition() {
 505             return position == null ? 0.5F : position.get();
 506         }
 507 
 508         public final DoubleProperty positionProperty() {
 509             if (position == null) {
 510                 position = new SimpleDoubleProperty(this, "position", 0.5F);// {
 511 //                    @Override protected void invalidated() {
 512 //                        if (get() < 0) {
 513 //                            this.value = value;
 514 //                        } else if (get() > 1) {
 515 //                            this.value = value;
 516 //                        }
 517 //                    }
 518 //                };
 519             }
 520             return position;
 521         }
 522     }
 523 }