1 /*
   2  * Copyright (c) 2010, 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.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 com.sun.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 #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      * Constructors                                                            *
 127      *                                                                         *
 128      **************************************************************************/
 129 
 130     /**
 131      * Create a new ContextMenu
 132      */
 133     public ContextMenu() {
 134         getStyleClass().setAll(DEFAULT_STYLE_CLASS);
 135         setAutoHide(true);
 136         setConsumeAutoHidingEvents(false);
 137     }
 138 
 139     /**
 140      * Create a new ContextMenu initialized with the given items
 141      */
 142     public ContextMenu(MenuItem... items) {
 143         this();
 144         this.items.addAll(items);
 145     }
 146 
 147     /***************************************************************************
 148      *                                                                         *
 149      * Properties                                                              *
 150      *                                                                         *
 151      **************************************************************************/
 152 
 153     /**
 154      * Callback function to be informed when an item contained within this
 155      * {@code ContextMenu} has been activated. The current implementation informs
 156      * all parent menus as well, so that it is not necessary to listen to all
 157      * sub menus for events.
 158      */
 159     private ObjectProperty<EventHandler<ActionEvent>> onAction = new ObjectPropertyBase<EventHandler<ActionEvent>>() {
 160         @Override protected void invalidated() {
 161             setEventHandler(ActionEvent.ACTION, get());
 162        }
 163 
 164         @Override
 165         public Object getBean() {
 166             return ContextMenu.this;
 167         }
 168 
 169         @Override
 170         public String getName() {
 171             return "onAction";
 172         }
 173     };
 174     public final void setOnAction(EventHandler<ActionEvent> value) { onActionProperty().set(value); }
 175     public final EventHandler<ActionEvent> getOnAction() { return onActionProperty().get(); }
 176     public final ObjectProperty<EventHandler<ActionEvent>> onActionProperty() { return onAction; }
 177 
 178     private final ObservableList<MenuItem> items = new TrackableObservableList<MenuItem>() {
 179         @Override protected void onChanged(Change<MenuItem> c) {
 180             while (c.next()) {
 181                 for (MenuItem item : c.getRemoved()) {
 182                     item.setParentPopup(null);
 183                 }
 184                 for (MenuItem item : c.getAddedSubList()) {
 185                     if (item.getParentPopup() != null) {
 186                         // we need to remove this item from its current parentPopup
 187                         // as a MenuItem should not exist in multiple parentPopup
 188                         // instances
 189                         item.getParentPopup().getItems().remove(item);
 190                     }
 191                     item.setParentPopup(ContextMenu.this);
 192                 }
 193             }
 194         }
 195     };
 196     /**
 197      * The menu items on the context menu. If this ObservableList is modified at
 198      * runtime, the ContextMenu will update as expected.
 199      * @see MenuItem
 200      */
 201     public final ObservableList<MenuItem> getItems() { return items; }
 202 
 203      /**
 204      * @treatAsPrivate implementation detail
 205      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
 206      */
 207     @Deprecated
 208     private final BooleanProperty impl_showRelativeToWindow = new SimpleBooleanProperty(false);
 209      /**
 210       * @treatAsPrivate implementation detail
 211       */
 212     public final boolean isImpl_showRelativeToWindow() { return impl_showRelativeToWindow.get(); }
 213      /**
 214       * @treatAsPrivate implementation detail
 215       */
 216     public final void setImpl_showRelativeToWindow(boolean value) { impl_showRelativeToWindow.set(value); }
 217      /**
 218       * @treatAsPrivate implementation detail
 219       */
 220     public final BooleanProperty impl_showRelativeToWindowProperty() { return impl_showRelativeToWindow; }
 221     
 222     /***************************************************************************
 223      *                                                                         *
 224      * Methods                                                                 *
 225      *                                                                         *
 226      **************************************************************************/
 227 
 228     /**
 229      * Shows the {@code ContextMenu} relative to the given anchor node, on the side
 230      * specified by the {@code hpos} and {@code vpos} parameters, and offset
 231      * by the given {@code dx} and {@code dy} values for the x-axis and y-axis, respectively.
 232      * If there is not enough room, the menu is moved to the opposite side and
 233      * the offset is not applied.
 234      * <p>
 235      * To clarify the purpose of the {@code hpos} and {@code vpos} parameters,
 236      * consider that they are relative to the anchor node. As such, a {@code hpos}
 237      * and {@code vpos} of {@code CENTER} would mean that the ContextMenu appears
 238      * on top of the anchor, with the (0,0) position of the {@code ContextMenu}
 239      * positioned at (0,0) of the anchor. A {@code hpos} of right would then shift
 240      * the {@code ContextMenu} such that its top-left (0,0) position would be attached
 241      * to the top-right position of the anchor.
 242      * <p>
 243      * This function is useful for finely tuning the position of a menu,
 244      * relative to the parent node to ensure close alignment.
 245      */
 246     // TODO provide more detail
 247      public void show(Node anchor, Side side, double dx, double dy) {
 248         if (anchor == null) return;
 249         if (getItems().size() == 0) return;
 250 
 251         getScene().setNodeOrientation(anchor.getEffectiveNodeOrientation());
 252         // FIXME because Side is not yet in javafx.geometry, we have to convert
 253         // to the old HPos/VPos API here, as Utils can not refer to Side in the
 254         // charting API.
 255         HPos hpos = side == Side.LEFT ? HPos.LEFT : side == Side.RIGHT ? HPos.RIGHT : HPos.CENTER;
 256         VPos vpos = side == Side.TOP ? VPos.TOP : side == Side.BOTTOM ? VPos.BOTTOM : VPos.CENTER;
 257 
 258         // translate from anchor/hpos/vpos/dx/dy into screenX/screenY
 259         Point2D point = Utils.pointRelativeTo(anchor,
 260                 prefWidth(-1), prefHeight(-1),
 261                 hpos, vpos, dx, dy, true);
 262         doShow(anchor, point.getX(), point.getY());
 263     }
 264 
 265      /**
 266      * Shows the {@code ContextMenu} at the specified screen coordinates. If there
 267      * is not enough room at the specified location to show the {@code ContextMenu}
 268      * given its size requirements, the necessary adjustments are made to bring
 269      * the {@code ContextMenu} back back on screen. This also means that the
 270      * {@code ContextMenu} will not span multiple monitors.
 271      */
 272     public void show(Node anchor, double screenX, double screenY) {
 273         if (anchor == null) return;
 274         if (getItems().size() == 0) return;
 275         getScene().setNodeOrientation(anchor.getEffectiveNodeOrientation());
 276         doShow(anchor, screenX, screenY);
 277     }
 278 
 279     private void doShow(Node anchor, double screenX, double screenY) {
 280         Event.fireEvent(this, new Event(Menu.ON_SHOWING));
 281         if(isImpl_showRelativeToWindow()) {
 282             final Scene scene = (anchor == null) ? null : anchor.getScene();
 283             final Window win = (scene == null) ? null : scene.getWindow();
 284             if (win == null) return;
 285             super.show(win, screenX, screenY);
 286         } else {
 287             super.show(anchor, screenX, screenY);
 288         }
 289         Event.fireEvent(this, new Event(Menu.ON_SHOWN));
 290     }
 291 
 292     /**
 293      * Hides this {@code ContextMenu} and any visible submenus, assuming that when this function
 294      * is called that the {@code ContextMenu} was showing.
 295      * <p>
 296      * If this {@code ContextMenu} is not showing, then nothing happens.
 297      */
 298     @Override public void hide() {
 299         if (!isShowing()) return;
 300         Event.fireEvent(this, new Event(Menu.ON_HIDING));
 301         super.hide();
 302         Event.fireEvent(this, new Event(Menu.ON_HIDDEN));
 303     }
 304 
 305     /** {@inheritDoc} */
 306     @Override protected Skin<?> createDefaultSkin() {
 307         return new ContextMenuSkin(this);
 308     }
 309 
 310     /***************************************************************************
 311      *                                                                         *
 312      *                         Stylesheet Handling                             *
 313      *                                                                         *
 314      ***************************************************************************/
 315 
 316     private static final String DEFAULT_STYLE_CLASS = "context-menu";
 317 }