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.skin;
  27 
  28 import com.sun.javafx.scene.ParentHelper;
  29 import com.sun.javafx.scene.control.FakeFocusTextField;
  30 import com.sun.javafx.scene.control.Properties;
  31 import com.sun.javafx.scene.control.behavior.TextInputControlBehavior;
  32 import com.sun.javafx.scene.input.ExtendedInputMethodRequests;
  33 import com.sun.javafx.scene.traversal.Algorithm;
  34 import com.sun.javafx.scene.traversal.Direction;
  35 import com.sun.javafx.scene.traversal.ParentTraversalEngine;
  36 import com.sun.javafx.scene.traversal.TraversalContext;
  37 import javafx.beans.InvalidationListener;
  38 import javafx.beans.value.ObservableValue;
  39 import javafx.css.Styleable;
  40 import javafx.event.EventHandler;
  41 import javafx.geometry.Bounds;
  42 import javafx.geometry.HPos;
  43 import javafx.geometry.Point2D;
  44 import javafx.geometry.VPos;
  45 import javafx.scene.AccessibleAttribute;
  46 import javafx.scene.Node;
  47 import javafx.scene.control.ComboBoxBase;
  48 import javafx.scene.control.PopupControl;
  49 import javafx.scene.control.Skin;
  50 import javafx.scene.control.Skinnable;
  51 import javafx.scene.control.TextField;
  52 import javafx.scene.input.DragEvent;
  53 import javafx.scene.input.KeyCode;
  54 import javafx.scene.input.KeyEvent;
  55 import javafx.scene.input.MouseEvent;
  56 import javafx.scene.layout.Region;
  57 import javafx.stage.WindowEvent;
  58 import javafx.util.StringConverter;
  59 
  60 /**
  61  * An abstract class that extends the functionality of {@link ComboBoxBaseSkin}
  62  * to include API related to showing ComboBox-like controls as popups.
  63  *
  64  * @param <T> The type of the ComboBox-like control.
  65  * @since 9
  66  */
  67 public abstract class ComboBoxPopupControl<T> extends ComboBoxBaseSkin<T> {
  68 
  69     /***************************************************************************
  70      *                                                                         *
  71      * Private fields                                                          *
  72      *                                                                         *
  73      **************************************************************************/
  74 
  75     PopupControl popup;
  76 
  77     private boolean popupNeedsReconfiguring = true;
  78 
  79     private final ComboBoxBase<T> comboBoxBase;
  80     private TextField textField;
  81 
  82     private String initialTextFieldValue = null;
  83 
  84 
  85 
  86     /***************************************************************************
  87      *                                                                         *
  88      * TextField Listeners                                                     *
  89      *                                                                         *
  90      **************************************************************************/
  91 
  92     private EventHandler<MouseEvent> textFieldMouseEventHandler = event -> {
  93         ComboBoxBase<T> comboBoxBase = getSkinnable();
  94         if (!event.getTarget().equals(comboBoxBase)) {
  95             comboBoxBase.fireEvent(event.copyFor(comboBoxBase, comboBoxBase));
  96             event.consume();
  97         }
  98     };
  99     private EventHandler<DragEvent> textFieldDragEventHandler = event -> {
 100         ComboBoxBase<T> comboBoxBase = getSkinnable();
 101         if (!event.getTarget().equals(comboBoxBase)) {
 102             comboBoxBase.fireEvent(event.copyFor(comboBoxBase, comboBoxBase));
 103             event.consume();
 104         }
 105     };
 106 
 107 
 108 
 109     /***************************************************************************
 110      *                                                                         *
 111      * Constructors                                                            *
 112      *                                                                         *
 113      **************************************************************************/
 114 
 115     /**
 116      * Creates a new instance of ComboBoxPopupControl, although note that this
 117      * instance does not handle any behavior / input mappings - this needs to be
 118      * handled appropriately by subclasses.
 119      *
 120      * @param control The control that this skin should be installed onto.
 121      */
 122     public ComboBoxPopupControl(ComboBoxBase<T> control) {
 123         super(control);
 124         this.comboBoxBase = control;
 125 
 126         // editable input node
 127         this.textField = getEditor() != null ? getEditableInputNode() : null;
 128 
 129         // Fix for RT-29565. Without this the textField does not have a correct
 130         // pref width at startup, as it is not part of the scenegraph (and therefore
 131         // has no pref width until after the first measurements have been taken).
 132         if (this.textField != null) {
 133             getChildren().add(textField);
 134         }
 135 
 136         // move fake focus in to the textfield if the comboBox is editable
 137         comboBoxBase.focusedProperty().addListener((ov, t, hasFocus) -> {
 138             if (getEditor() != null) {
 139                 // Fix for the regression noted in a comment in RT-29885.
 140                 ((FakeFocusTextField)textField).setFakeFocus(hasFocus);
 141             }
 142         });
 143 
 144         comboBoxBase.addEventFilter(KeyEvent.ANY, ke -> {
 145             if (textField == null || getEditor() == null) {
 146                 handleKeyEvent(ke, false);
 147             } else {
 148                 // This prevents a stack overflow from our rebroadcasting of the
 149                 // event to the textfield that occurs in the final else statement
 150                 // of the conditions below.
 151                 if (ke.getTarget().equals(textField)) return;
 152 
 153                 switch (ke.getCode()) {
 154                   case ESCAPE:
 155                   case F10:
 156                       // Allow to bubble up.
 157                       break;
 158 
 159                   case ENTER:
 160                     handleKeyEvent(ke, true);
 161                     break;
 162 
 163                   default:
 164                     // Fix for the regression noted in a comment in RT-29885.
 165                     // This forwards the event down into the TextField when
 166                     // the key event is actually received by the ComboBox.
 167                     textField.fireEvent(ke.copyFor(textField, textField));
 168                     ke.consume();
 169                 }
 170             }
 171         });
 172 
 173         // RT-38978: Forward input method events to TextField if editable.
 174         if (comboBoxBase.getOnInputMethodTextChanged() == null) {
 175             comboBoxBase.setOnInputMethodTextChanged(event -> {
 176                 if (textField != null && getEditor() != null && comboBoxBase.getScene().getFocusOwner() == comboBoxBase) {
 177                     if (textField.getOnInputMethodTextChanged() != null) {
 178                         textField.getOnInputMethodTextChanged().handle(event);
 179                     }
 180                 }
 181             });
 182         }
 183 
 184         // Fix for RT-36902, where focus traversal was getting stuck inside the ComboBox
 185         ParentHelper.setTraversalEngine(comboBoxBase,
 186                 new ParentTraversalEngine(comboBoxBase, new Algorithm() {
 187 
 188             @Override public Node select(Node owner, Direction dir, TraversalContext context) {
 189                 return null;
 190             }
 191 
 192             @Override public Node selectFirst(TraversalContext context) {
 193                 return null;
 194             }
 195 
 196             @Override public Node selectLast(TraversalContext context) {
 197                 return null;
 198             }
 199         }));
 200 
 201         updateEditable();
 202     }
 203 
 204 
 205 
 206     /***************************************************************************
 207      *                                                                         *
 208      * Public API                                                              *
 209      *                                                                         *
 210      **************************************************************************/
 211 
 212     /**
 213      * This method should return the Node that will be displayed when the user
 214      * clicks on the ComboBox 'button' area.
 215      */
 216     protected abstract Node getPopupContent();
 217 
 218     /**
 219      * Subclasses are responsible for getting the editor. This will be removed
 220      * in FX 9 when the editor property is moved up to ComboBoxBase with
 221      * JDK-8130354
 222      *
 223      * Note: ComboBoxListViewSkin should return null if editable is false, even
 224      * if the ComboBox does have an editor set.
 225      */
 226     protected abstract TextField getEditor();
 227 
 228     /**
 229      * Subclasses are responsible for getting the converter. This will be
 230      * removed in FX 9 when the converter property is moved up to ComboBoxBase
 231      * with JDK-8130354.
 232      */
 233     protected abstract StringConverter<T> getConverter();
 234 
 235     /** {@inheritDoc} */
 236     @Override public void show() {
 237         if (getSkinnable() == null) {
 238             throw new IllegalStateException("ComboBox is null");
 239         }
 240 
 241         Node content = getPopupContent();
 242         if (content == null) {
 243             throw new IllegalStateException("Popup node is null");
 244         }
 245 
 246         if (getPopup().isShowing()) return;
 247 
 248         positionAndShowPopup();
 249     }
 250 
 251     /** {@inheritDoc} */
 252     @Override public void hide() {
 253         if (popup != null && popup.isShowing()) {
 254             popup.hide();
 255         }
 256     }
 257 
 258 
 259 
 260     /***************************************************************************
 261      *                                                                         *
 262      * Private implementation                                                  *
 263      *                                                                         *
 264      **************************************************************************/
 265 
 266     PopupControl getPopup() {
 267         if (popup == null) {
 268             createPopup();
 269         }
 270         return popup;
 271     }
 272 
 273     TextField getEditableInputNode() {
 274         if (textField == null && getEditor() != null) {
 275             textField = getEditor();
 276             textField.setFocusTraversable(false);
 277             textField.promptTextProperty().bind(comboBoxBase.promptTextProperty());
 278             textField.tooltipProperty().bind(comboBoxBase.tooltipProperty());
 279 
 280             // Fix for JDK-8145515 - in short the ComboBox was firing the event down to
 281             // the TextField, and then the TextField was firing it back up to the
 282             // ComboBox, resulting in stack overflows.
 283             textField.getProperties().put(TextInputControlBehavior.DISABLE_FORWARD_TO_PARENT, true);
 284 
 285             // Fix for RT-21406: ComboBox do not show initial text value
 286             initialTextFieldValue = textField.getText();
 287             // End of fix (see updateDisplayNode below for the related code)
 288         }
 289 
 290         return textField;
 291     }
 292 
 293     void setTextFromTextFieldIntoComboBoxValue() {
 294         if (getEditor() != null) {
 295             StringConverter<T> c = getConverter();
 296             if (c != null) {
 297                 T oldValue = comboBoxBase.getValue();
 298                 T value = oldValue;
 299                 String text = textField.getText();
 300 
 301                 // conditional check here added due to RT-28245
 302                 if (oldValue == null && (text == null || text.isEmpty())) {
 303                     value = null;
 304                 } else {
 305                     try {
 306                         value = c.fromString(text);
 307                     } catch (Exception ex) {
 308                         // Most likely a parsing error, such as DateTimeParseException
 309                     }
 310                 }
 311 
 312                 if ((value != null || oldValue != null) && (value == null || !value.equals(oldValue))) {
 313                     // no point updating values needlessly if they are the same
 314                     comboBoxBase.setValue(value);
 315                 }
 316 
 317                 updateDisplayNode();
 318             }
 319         }
 320     }
 321 
 322     void updateDisplayNode() {
 323         if (textField != null && getEditor() != null) {
 324             T value = comboBoxBase.getValue();
 325             StringConverter<T> c = getConverter();
 326 
 327             if (initialTextFieldValue != null && ! initialTextFieldValue.isEmpty()) {
 328                 // Remainder of fix for RT-21406: ComboBox do not show initial text value
 329                 textField.setText(initialTextFieldValue);
 330                 initialTextFieldValue = null;
 331                 // end of fix
 332             } else {
 333                 String stringValue = c.toString(value);
 334                 if (value == null || stringValue == null) {
 335                     textField.setText("");
 336                 } else if (! stringValue.equals(textField.getText())) {
 337                     textField.setText(stringValue);
 338                 }
 339             }
 340         }
 341     }
 342 
 343     void updateEditable() {
 344         TextField newTextField = getEditor();
 345 
 346         if (getEditor() == null) {
 347             // remove event filters
 348             if (textField != null) {
 349                 textField.removeEventFilter(MouseEvent.DRAG_DETECTED, textFieldMouseEventHandler);
 350                 textField.removeEventFilter(DragEvent.ANY, textFieldDragEventHandler);
 351 
 352                 comboBoxBase.setInputMethodRequests(null);
 353             }
 354         } else if (newTextField != null) {
 355             // add event filters
 356 
 357             // Fix for RT-31093 - drag events from the textfield were not surfacing
 358             // properly for the ComboBox.
 359             newTextField.addEventFilter(MouseEvent.DRAG_DETECTED, textFieldMouseEventHandler);
 360             newTextField.addEventFilter(DragEvent.ANY, textFieldDragEventHandler);
 361 
 362             // RT-38978: Forward input method requests to TextField.
 363             comboBoxBase.setInputMethodRequests(new ExtendedInputMethodRequests() {
 364                 @Override public Point2D getTextLocation(int offset) {
 365                     return newTextField.getInputMethodRequests().getTextLocation(offset);
 366                 }
 367 
 368                 @Override public int getLocationOffset(int x, int y) {
 369                     return newTextField.getInputMethodRequests().getLocationOffset(x, y);
 370                 }
 371 
 372                 @Override public void cancelLatestCommittedText() {
 373                     newTextField.getInputMethodRequests().cancelLatestCommittedText();
 374                 }
 375 
 376                 @Override public String getSelectedText() {
 377                     return newTextField.getInputMethodRequests().getSelectedText();
 378                 }
 379 
 380                 @Override public int getInsertPositionOffset() {
 381                     return ((ExtendedInputMethodRequests)newTextField.getInputMethodRequests()).getInsertPositionOffset();
 382                 }
 383 
 384                 @Override public String getCommittedText(int begin, int end) {
 385                     return ((ExtendedInputMethodRequests)newTextField.getInputMethodRequests()).getCommittedText(begin, end);
 386                 }
 387 
 388                 @Override public int getCommittedTextLength() {
 389                     return ((ExtendedInputMethodRequests)newTextField.getInputMethodRequests()).getCommittedTextLength();
 390                 }
 391             });
 392         }
 393 
 394         textField = newTextField;
 395     }
 396 
 397     private Point2D getPrefPopupPosition() {
 398         return com.sun.javafx.util.Utils.pointRelativeTo(getSkinnable(), getPopupContent(), HPos.CENTER, VPos.BOTTOM, 0, 0, true);
 399     }
 400 
 401     private void positionAndShowPopup() {
 402         final PopupControl _popup = getPopup();
 403         _popup.getScene().setNodeOrientation(getSkinnable().getEffectiveNodeOrientation());
 404 
 405 
 406         final Node popupContent = getPopupContent();
 407         sizePopup();
 408 
 409         Point2D p = getPrefPopupPosition();
 410 
 411         popupNeedsReconfiguring = true;
 412         reconfigurePopup();
 413 
 414         final ComboBoxBase<T> comboBoxBase = getSkinnable();
 415         _popup.show(comboBoxBase.getScene().getWindow(),
 416                 snapPositionX(p.getX()),
 417                 snapPositionY(p.getY()));
 418 
 419         popupContent.requestFocus();
 420 
 421         // second call to sizePopup here to enable proper sizing _after_ the popup
 422         // has been displayed. See RT-37622 for more detail.
 423         sizePopup();
 424     }
 425 
 426     private void sizePopup() {
 427         final Node popupContent = getPopupContent();
 428 
 429         if (popupContent instanceof Region) {
 430             // snap to pixel
 431             final Region r = (Region) popupContent;
 432 
 433             // 0 is used here for the width due to RT-46097
 434             double prefHeight = snapSizeY(r.prefHeight(0));
 435             double minHeight = snapSizeY(r.minHeight(0));
 436             double maxHeight = snapSizeY(r.maxHeight(0));
 437             double h = snapSizeY(Math.min(Math.max(prefHeight, minHeight), Math.max(minHeight, maxHeight)));
 438 
 439             double prefWidth = snapSizeX(r.prefWidth(h));
 440             double minWidth = snapSizeX(r.minWidth(h));
 441             double maxWidth = snapSizeX(r.maxWidth(h));
 442             double w = snapSizeX(Math.min(Math.max(prefWidth, minWidth), Math.max(minWidth, maxWidth)));
 443 
 444             popupContent.resize(w, h);
 445         } else {
 446             popupContent.autosize();
 447         }
 448     }
 449 
 450     private void createPopup() {
 451         popup = new PopupControl() {
 452             @Override public Styleable getStyleableParent() {
 453                 return ComboBoxPopupControl.this.getSkinnable();
 454             }
 455             {
 456                 setSkin(new Skin<Skinnable>() {
 457                     @Override public Skinnable getSkinnable() { return ComboBoxPopupControl.this.getSkinnable(); }
 458                     @Override public Node getNode() { return getPopupContent(); }
 459                     @Override public void dispose() { }
 460                 });
 461             }
 462         };
 463         popup.getStyleClass().add(Properties.COMBO_BOX_STYLE_CLASS);
 464         popup.setConsumeAutoHidingEvents(false);
 465         popup.setAutoHide(true);
 466         popup.setAutoFix(true);
 467         popup.setHideOnEscape(true);
 468         popup.setOnAutoHide(e -> getBehavior().onAutoHide(popup));
 469         popup.addEventHandler(MouseEvent.MOUSE_CLICKED, t -> {
 470             // RT-18529: We listen to mouse input that is received by the popup
 471             // but that is not consumed, and assume that this is due to the mouse
 472             // clicking outside of the node, but in areas such as the
 473             // dropshadow.
 474             getBehavior().onAutoHide(popup);
 475         });
 476         popup.addEventHandler(WindowEvent.WINDOW_HIDDEN, t -> {
 477             // Make sure the accessibility focus returns to the combo box
 478             // after the window closes.
 479             getSkinnable().notifyAccessibleAttributeChanged(AccessibleAttribute.FOCUS_NODE);
 480         });
 481 
 482         // Fix for RT-21207
 483         InvalidationListener layoutPosListener = o -> {
 484             popupNeedsReconfiguring = true;
 485             reconfigurePopup();
 486         };
 487         getSkinnable().layoutXProperty().addListener(layoutPosListener);
 488         getSkinnable().layoutYProperty().addListener(layoutPosListener);
 489         getSkinnable().widthProperty().addListener(layoutPosListener);
 490         getSkinnable().heightProperty().addListener(layoutPosListener);
 491 
 492         // RT-36966 - if skinnable's scene becomes null, ensure popup is closed
 493         getSkinnable().sceneProperty().addListener(o -> {
 494             if (((ObservableValue)o).getValue() == null) {
 495                 hide();
 496             }
 497         });
 498 
 499     }
 500 
 501     void reconfigurePopup() {
 502         // RT-26861. Don't call getPopup() here because it may cause the popup
 503         // to be created too early, which leads to memory leaks like those noted
 504         // in RT-32827.
 505         if (popup == null) return;
 506 
 507         final boolean isShowing = popup.isShowing();
 508         if (! isShowing) return;
 509 
 510         if (! popupNeedsReconfiguring) return;
 511         popupNeedsReconfiguring = false;
 512 
 513         final Point2D p = getPrefPopupPosition();
 514 
 515         final Node popupContent = getPopupContent();
 516         final double minWidth = popupContent.prefWidth(Region.USE_COMPUTED_SIZE);
 517         final double minHeight = popupContent.prefHeight(Region.USE_COMPUTED_SIZE);
 518 
 519         if (p.getX() > -1) popup.setAnchorX(p.getX());
 520         if (p.getY() > -1) popup.setAnchorY(p.getY());
 521         if (minWidth > -1) popup.setMinWidth(minWidth);
 522         if (minHeight > -1) popup.setMinHeight(minHeight);
 523 
 524         final Bounds b = popupContent.getLayoutBounds();
 525         final double currentWidth = b.getWidth();
 526         final double currentHeight = b.getHeight();
 527         final double newWidth  = currentWidth < minWidth ? minWidth : currentWidth;
 528         final double newHeight = currentHeight < minHeight ? minHeight : currentHeight;
 529 
 530         if (newWidth != currentWidth || newHeight != currentHeight) {
 531             // Resizing content to resolve issues such as RT-32582 and RT-33700
 532             // (where RT-33700 was introduced due to a previous fix for RT-32582)
 533             popupContent.resize(newWidth, newHeight);
 534             if (popupContent instanceof Region) {
 535                 ((Region)popupContent).setMinSize(newWidth, newHeight);
 536                 ((Region)popupContent).setPrefSize(newWidth, newHeight);
 537             }
 538         }
 539     }
 540 
 541     private void handleKeyEvent(KeyEvent ke, boolean doConsume) {
 542         // When the user hits the enter or F4 keys, we respond before
 543         // ever giving the event to the TextField.
 544         if (ke.getCode() == KeyCode.ENTER) {
 545             if (ke.isConsumed() || ke.getEventType() != KeyEvent.KEY_RELEASED) {
 546                 return;
 547             }
 548             setTextFromTextFieldIntoComboBoxValue();
 549 
 550             if (doConsume && comboBoxBase.getOnAction() != null) {
 551                 ke.consume();
 552             } else if (textField != null) {
 553                 textField.fireEvent(ke);
 554             }
 555         } else if (ke.getCode() == KeyCode.F4) {
 556             if (ke.getEventType() == KeyEvent.KEY_RELEASED) {
 557                 if (comboBoxBase.isShowing()) comboBoxBase.hide();
 558                 else comboBoxBase.show();
 559             }
 560             ke.consume(); // we always do a consume here (otherwise unit tests fail)
 561         } else if (ke.getCode() == KeyCode.F10 || ke.getCode() == KeyCode.ESCAPE) {
 562             // RT-23275: The TextField fires F10 and ESCAPE key events
 563             // up to the parent, which are then fired back at the
 564             // TextField, and this ends up in an infinite loop until
 565             // the stack overflows. So, here we consume these two
 566             // events and stop them from going any further.
 567             if (doConsume) ke.consume();
 568         }
 569     }
 570 
 571 
 572 
 573     /***************************************************************************
 574      *                                                                         *
 575      * Support classes                                                         *
 576      *                                                                         *
 577      **************************************************************************/
 578 
 579 
 580 
 581 
 582 
 583     /***************************************************************************
 584      *                                                                         *
 585      * Stylesheet Handling                                                     *
 586      *                                                                         *
 587      **************************************************************************/
 588 
 589 }