1 /*
   2  * Copyright (c) 2010, 2017, 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 com.sun.javafx.beans.IDProperty;
  29 import javafx.beans.property.ObjectProperty;
  30 import javafx.beans.property.ObjectPropertyBase;
  31 import javafx.collections.ListChangeListener.Change;
  32 import javafx.collections.ObservableList;
  33 import javafx.event.ActionEvent;
  34 import javafx.event.Event;
  35 import javafx.event.EventHandler;
  36 import javafx.geometry.HPos;
  37 import javafx.geometry.Point2D;
  38 import javafx.geometry.Side;
  39 import javafx.geometry.VPos;
  40 import javafx.scene.Node;
  41 import javafx.scene.Scene;
  42 import javafx.stage.Window;
  43 
  44 import com.sun.javafx.util.Utils;
  45 import com.sun.javafx.collections.TrackableObservableList;
  46 import javafx.scene.control.skin.ContextMenuSkin;
  47 import javafx.beans.property.BooleanProperty;
  48 import javafx.beans.property.SimpleBooleanProperty;
  49 
  50 /**
  51  * <p>
  52  * A popup control containing an ObservableList of menu items. The {@link #getItems() items}
  53  * ObservableList allows for any {@link MenuItem} type to be inserted,
  54  * including its subclasses {@link Menu}, {@link MenuItem}, {@link RadioMenuItem}, {@link CheckMenuItem} and
  55  * {@link CustomMenuItem}. If an arbitrary Node needs to be
  56  * inserted into a menu, a CustomMenuItem can be used. One exception to this general rule is that
  57  * {@link SeparatorMenuItem} could be used for inserting a separator.
  58  * <p>
  59  * A common use case for this class is creating and showing context menus to
  60  * users. To create a context menu using ContextMenu you can do the
  61  * following:
  62 <pre><code>
  63 final ContextMenu contextMenu = new ContextMenu();
  64 contextMenu.setOnShowing(new EventHandler&lt;WindowEvent&gt;() {
  65     public void handle(WindowEvent e) {
  66         System.out.println("showing");
  67     }
  68 });
  69 contextMenu.setOnShown(new EventHandler&lt;WindowEvent&gt;() {
  70     public void handle(WindowEvent e) {
  71         System.out.println("shown");
  72     }
  73 });
  74 
  75 MenuItem item1 = new MenuItem("About");
  76 item1.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
  77     public void handle(ActionEvent e) {
  78         System.out.println("About");
  79     }
  80 });
  81 MenuItem item2 = new MenuItem("Preferences");
  82 item2.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
  83     public void handle(ActionEvent e) {
  84         System.out.println("Preferences");
  85     }
  86 });
  87 contextMenu.getItems().addAll(item1, item2);
  88 
  89 final TextField textField = new TextField("Type Something");
  90 textField.setContextMenu(contextMenu);
  91 </code></pre>
  92  *
  93  * <p>{@link Control#setContextMenu(javafx.scene.control.ContextMenu) } convenience
  94  * method can be used to set a context menu on on any control. The example above results in the
  95  * context menu being displayed on the right {@link javafx.geometry.Side Side}
  96  * of the TextField. Alternatively, an event handler can also be set on the control
  97  * to invoke the context menu as shown below.
  98  * <pre><code>
  99 textField.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
 100     public void handle(ActionEvent e) {
 101         contextMenu.show(textField, Side.BOTTOM, 0, 0);
 102     }
 103 });
 104 
 105 Group root = (Group) scene.getRoot();
 106 root.getChildren().add(textField);
 107 </code></pre>
 108  *
 109  * <p>In this example, the context menu is shown when the user clicks on the
 110  * {@link javafx.scene.control.Button Button} (of course, you should use the
 111  * {@link MenuButton} control to do this rather than doing the above).</p>
 112  *
 113  * <p>Note that the show function used in the code sample
 114  * above will result in the ContextMenu appearing directly beneath the
 115  * TextField. You can vary the {@link javafx.geometry.Side Side}  to get the results you expect.</p>
 116  *
 117  * @see MenuItem
 118  * @see Menu
 119  * @since JavaFX 2.0
 120  */
 121 @IDProperty("id")
 122 public class ContextMenu extends PopupControl {
 123 
 124     /***************************************************************************
 125      *                                                                         *
 126      * Fields                                                                  *
 127      *                                                                         *
 128      **************************************************************************/
 129 
 130     private boolean showRelativeToWindow = false;
 131 
 132 
 133 
 134     /***************************************************************************
 135      *                                                                         *
 136      * Constructors                                                            *
 137      *                                                                         *
 138      **************************************************************************/
 139 
 140     /**
 141      * Create a new ContextMenu
 142      */
 143     public ContextMenu() {
 144         getStyleClass().setAll(DEFAULT_STYLE_CLASS);
 145         setAutoHide(true);
 146         setConsumeAutoHidingEvents(false);
 147     }
 148 
 149     /**
 150      * Create a new ContextMenu initialized with the given items
 151      * @param items the list of menu items
 152      */
 153     public ContextMenu(MenuItem... items) {
 154         this();
 155         this.items.addAll(items);
 156     }
 157 
 158 
 159 
 160     /***************************************************************************
 161      *                                                                         *
 162      * Properties                                                              *
 163      *                                                                         *
 164      **************************************************************************/
 165 
 166     /**
 167      * Callback function to be informed when an item contained within this
 168      * {@code ContextMenu} has been activated. The current implementation informs
 169      * all parent menus as well, so that it is not necessary to listen to all
 170      * sub menus for events.
 171      */
 172     private ObjectProperty<EventHandler<ActionEvent>> onAction = new ObjectPropertyBase<EventHandler<ActionEvent>>() {
 173         @Override protected void invalidated() {
 174             setEventHandler(ActionEvent.ACTION, get());
 175        }
 176 
 177         @Override
 178         public Object getBean() {
 179             return ContextMenu.this;
 180         }
 181 
 182         @Override
 183         public String getName() {
 184             return "onAction";
 185         }
 186     };
 187     public final void setOnAction(EventHandler<ActionEvent> value) { onActionProperty().set(value); }
 188     public final EventHandler<ActionEvent> getOnAction() { return onActionProperty().get(); }
 189     public final ObjectProperty<EventHandler<ActionEvent>> onActionProperty() { return onAction; }
 190 
 191     private final ObservableList<MenuItem> items = new TrackableObservableList<MenuItem>() {
 192         @Override protected void onChanged(Change<MenuItem> c) {
 193             while (c.next()) {
 194                 for (MenuItem item : c.getRemoved()) {
 195                     item.setParentPopup(null);
 196                 }
 197                 for (MenuItem item : c.getAddedSubList()) {
 198                     if (item.getParentPopup() != null) {
 199                         // we need to remove this item from its current parentPopup
 200                         // as a MenuItem should not exist in multiple parentPopup
 201                         // instances
 202                         item.getParentPopup().getItems().remove(item);
 203                     }
 204                     item.setParentPopup(ContextMenu.this);
 205                 }
 206             }
 207         }
 208     };
 209 
 210 
 211 
 212     /***************************************************************************
 213      *                                                                         *
 214      * Public API                                                              *
 215      *                                                                         *
 216      **************************************************************************/
 217 
 218     /**
 219      * The menu items on the context menu. If this ObservableList is modified at
 220      * runtime, the ContextMenu will update as expected.
 221      * @return the menu items on this context menu
 222      * @see MenuItem
 223      */
 224     public final ObservableList<MenuItem> getItems() { return items; }
 225 
 226     /**
 227      * Shows the {@code ContextMenu} relative to the given anchor node, on the side
 228      * specified by the {@code hpos} and {@code vpos} parameters, and offset
 229      * by the given {@code dx} and {@code dy} values for the x-axis and y-axis, respectively.
 230      * If there is not enough room, the menu is moved to the opposite side and
 231      * the offset is not applied.
 232      * <p>
 233      * To clarify the purpose of the {@code hpos} and {@code vpos} parameters,
 234      * consider that they are relative to the anchor node. As such, a {@code hpos}
 235      * and {@code vpos} of {@code CENTER} would mean that the ContextMenu appears
 236      * on top of the anchor, with the (0,0) position of the {@code ContextMenu}
 237      * positioned at (0,0) of the anchor. A {@code hpos} of right would then shift
 238      * the {@code ContextMenu} such that its top-left (0,0) position would be attached
 239      * to the top-right position of the anchor.
 240      * <p>
 241      * This function is useful for finely tuning the position of a menu,
 242      * relative to the parent node to ensure close alignment.
 243      * @param anchor the anchor node
 244      * @param side the side
 245      * @param dx the dx value for the x-axis
 246      * @param dy the dy value for the y-axis
 247      */
 248     // TODO provide more detail
 249      public void show(Node anchor, Side side, double dx, double dy) {
 250         if (anchor == null) return;
 251         if (getItems().size() == 0) return;
 252 
 253         getScene().setNodeOrientation(anchor.getEffectiveNodeOrientation());
 254         // FIXME because Side is not yet in javafx.geometry, we have to convert
 255         // to the old HPos/VPos API here, as Utils can not refer to Side in the
 256         // charting API.
 257         HPos hpos = side == Side.LEFT ? HPos.LEFT : side == Side.RIGHT ? HPos.RIGHT : HPos.CENTER;
 258         VPos vpos = side == Side.TOP ? VPos.TOP : side == Side.BOTTOM ? VPos.BOTTOM : VPos.CENTER;
 259 
 260         // translate from anchor/hpos/vpos/dx/dy into screenX/screenY
 261         Point2D point = Utils.pointRelativeTo(anchor,
 262                 prefWidth(-1), prefHeight(-1),
 263                 hpos, vpos, dx, dy, true);
 264         doShow(anchor, point.getX(), point.getY());
 265     }
 266 
 267      /**
 268      * Shows the {@code ContextMenu} at the specified screen coordinates. If there
 269      * is not enough room at the specified location to show the {@code ContextMenu}
 270      * given its size requirements, the necessary adjustments are made to bring
 271      * the {@code ContextMenu} back back on screen. This also means that the
 272      * {@code ContextMenu} will not span multiple monitors.
 273      * @param anchor the anchor node
 274      * @param screenX the x position of the anchor in screen coordinates
 275      * @param screenY the y position of the anchor in screen coordinates
 276      */
 277     @Override
 278     public void show(Node anchor, double screenX, double screenY) {
 279         if (anchor == null) return;
 280         if (getItems().size() == 0) return;
 281         getScene().setNodeOrientation(anchor.getEffectiveNodeOrientation());
 282         doShow(anchor, screenX, screenY);
 283     }
 284 
 285     /**
 286      * Hides this {@code ContextMenu} and any visible submenus, assuming that when this function
 287      * is called that the {@code ContextMenu} was showing.
 288      * <p>
 289      * If this {@code ContextMenu} is not showing, then nothing happens.
 290      */
 291     @Override public void hide() {
 292         if (!isShowing()) return;
 293         Event.fireEvent(this, new Event(Menu.ON_HIDING));
 294         super.hide();
 295         Event.fireEvent(this, new Event(Menu.ON_HIDDEN));
 296     }
 297 
 298     /** {@inheritDoc} */
 299     @Override protected Skin<?> createDefaultSkin() {
 300         return new ContextMenuSkin(this);
 301     }
 302 
 303 
 304 
 305     /***************************************************************************
 306      *                                                                         *
 307      * Private Implementation                                                  *
 308      *                                                                         *
 309      **************************************************************************/
 310 
 311     final boolean isShowRelativeToWindow() { return showRelativeToWindow; }
 312     final void setShowRelativeToWindow(boolean value) { showRelativeToWindow = value; }
 313 
 314     private void doShow(Node anchor, double screenX, double screenY) {
 315         Event.fireEvent(this, new Event(Menu.ON_SHOWING));
 316         if(isShowRelativeToWindow()) {
 317             final Scene scene = (anchor == null) ? null : anchor.getScene();
 318             final Window win = (scene == null) ? null : scene.getWindow();
 319             if (win == null) return;
 320             super.show(win, screenX, screenY);
 321         } else {
 322             super.show(anchor, screenX, screenY);
 323         }
 324         Event.fireEvent(this, new Event(Menu.ON_SHOWN));
 325     }
 326 
 327 
 328 
 329     /***************************************************************************
 330      *                                                                         *
 331      *                         Stylesheet Handling                             *
 332      *                                                                         *
 333      ***************************************************************************/
 334 
 335     private static final String DEFAULT_STYLE_CLASS = "context-menu";
 336 }