1 /*
   2  * Copyright (c) 2011, 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 com.apple.laf;
  27 
  28 import java.awt.*;
  29 import java.awt.event.*;
  30 import java.awt.peer.MenuComponentPeer;
  31 import java.util.Hashtable;
  32 
  33 import javax.swing.*;
  34 
  35 import sun.awt.SunToolkit;
  36 import sun.lwawt.LWToolkit;
  37 import sun.lwawt.macosx.*;
  38 
  39 @SuppressWarnings("serial") // JDK implementation class
  40 final class ScreenMenu extends Menu
  41         implements ContainerListener, ComponentListener,
  42                    ScreenMenuPropertyHandler {
  43 
  44     static {
  45         java.security.AccessController.doPrivileged(
  46             new java.security.PrivilegedAction<Void>() {
  47                 public Void run() {
  48                     System.loadLibrary("awt");
  49                     return null;
  50                 }
  51             });
  52     }
  53 
  54     // screen menu stuff
  55     private static native long addMenuListeners(ScreenMenu listener, long nativeMenu);
  56     private static native void removeMenuListeners(long modelPtr);
  57 
  58     private transient long fModelPtr;
  59 
  60     private final Hashtable<Component, MenuItem> fItems;
  61     private final JMenu fInvoker;
  62 
  63     private Component fLastMouseEventTarget;
  64     private Rectangle fLastTargetRect;
  65     private volatile Rectangle[] fItemBounds;
  66 
  67     private ScreenMenuPropertyListener fPropertyListener;
  68 
  69     // Array of child hashes used to see if we need to recreate the Menu.
  70     private int childHashArray[];
  71 
  72     ScreenMenu(final JMenu invoker) {
  73         super(invoker.getText());
  74         fInvoker = invoker;
  75 
  76         int count = fInvoker.getMenuComponentCount();
  77         if (count < 5) count = 5;
  78         fItems = new Hashtable<Component, MenuItem>(count);
  79         setEnabled(fInvoker.isEnabled());
  80         updateItems();
  81     }
  82 
  83     /**
  84      * Determine if we need to tear down the Menu and re-create it, since the contents may have changed in the Menu opened listener and
  85      * we do not get notified of it, because EDT is busy in our code. We only need to update if the menu contents have changed in some
  86      * way, such as the number of menu items, the text of the menuitems, icon, shortcut etc.
  87      */
  88     private static boolean needsUpdate(final Component items[], final int childHashArray[]) {
  89       if (items == null || childHashArray == null) {
  90         return true;
  91       }
  92       if (childHashArray.length != items.length) {
  93        return true;
  94       }
  95       for (int i = 0; i < items.length; i++) {
  96           final int hashCode = getHashCode(items[i]);
  97           if (hashCode != childHashArray[i]) {
  98             return true;
  99           }
 100       }
 101       return false;
 102     }
 103 
 104     /**
 105      * Used to recreate the AWT based Menu structure that implements the Screen Menu.
 106      * Also computes hashcode and stores them so that we can compare them later in needsUpdate.
 107      */
 108     private void updateItems() {
 109         final int count = fInvoker.getMenuComponentCount();
 110         final Component[] items = fInvoker.getMenuComponents();
 111         if (needsUpdate(items, childHashArray)) {
 112             removeAll();
 113             if (count <= 0) return;
 114 
 115             childHashArray = new int[count];
 116             for (int i = 0; i < count; i++) {
 117                 addItem(items[i]);
 118                 childHashArray[i] = getHashCode(items[i]);
 119             }
 120         }
 121     }
 122 
 123     /**
 124      * Callback from JavaMenuUpdater.m -- called when menu first opens
 125      */
 126     public void invokeOpenLater() {
 127         final JMenu invoker = fInvoker;
 128         if (invoker == null) {
 129             System.err.println("invoker is null!");
 130             return;
 131         }
 132 
 133         try {
 134             LWCToolkit.invokeAndWait(new Runnable() {
 135                 public void run() {
 136                     invoker.setSelected(true);
 137                     invoker.validate();
 138                     updateItems();
 139                     fItemBounds = new Rectangle[invoker.getMenuComponentCount()];
 140                 }
 141             }, invoker);
 142         } catch (final Exception e) {
 143             System.err.println(e);
 144             e.printStackTrace();
 145         }
 146     }
 147 
 148     /**
 149      * Callback from JavaMenuUpdater.m -- called when menu closes.
 150      */
 151     public void invokeMenuClosing() {
 152         final JMenu invoker = fInvoker;
 153         if (invoker == null) return;
 154 
 155         try {
 156             LWCToolkit.invokeAndWait(new Runnable() {
 157                 public void run() {
 158                     invoker.setSelected(false);
 159                     // Null out the tracking rectangles and the array.
 160                     if (fItemBounds != null) {
 161                         for (int i = 0; i < fItemBounds.length; i++) {
 162                             fItemBounds[i] = null;
 163                         }
 164                     }
 165                     fItemBounds = null;
 166                 }
 167             }, invoker);
 168         } catch (final Exception e) {
 169             e.printStackTrace();
 170         }
 171     }
 172 
 173     /**
 174      * Callback from JavaMenuUpdater.m -- called when menu item is hilighted.
 175      *
 176      * @param inWhichItem The menu item selected by the user. -1 if mouse moves off the menu.
 177      * @param itemRectTop
 178      * @param itemRectLeft
 179      * @param itemRectBottom
 180      * @param itemRectRight Tracking rectangle coordinates.
 181      */
 182     public void handleItemTargeted(final int inWhichItem, final int itemRectTop, final int itemRectLeft, final int itemRectBottom, final int itemRectRight) {
 183         if (fItemBounds == null || inWhichItem < 0 || inWhichItem > (fItemBounds.length - 1)) return;
 184         final Rectangle itemRect = new Rectangle(itemRectLeft, itemRectTop, itemRectRight - itemRectLeft, itemRectBottom - itemRectTop);
 185         fItemBounds[inWhichItem] = itemRect;
 186     }
 187 
 188     /**
 189      * Callback from JavaMenuUpdater.m -- called when mouse event happens on the menu.
 190      */
 191     public void handleMouseEvent(final int kind, final int x, final int y, final int modifiers, final long when) {
 192         if (kind == 0) return;
 193         if (fItemBounds == null) return;
 194 
 195         SunToolkit.executeOnEventHandlerThread(fInvoker, new Runnable() {
 196             @Override
 197             public void run() {
 198                 Component target = null;
 199                 Rectangle targetRect = null;
 200                 for (int i = 0; i < fItemBounds.length; i++) {
 201                     final Rectangle testRect = fItemBounds[i];
 202                     if (testRect != null) {
 203                         if (testRect.contains(x, y)) {
 204                             target = fInvoker.getMenuComponent(i);
 205                             targetRect = testRect;
 206                             break;
 207                         }
 208                     }
 209                 }
 210                 if (target == null && fLastMouseEventTarget == null) return;
 211 
 212                 // Send a mouseExited to the previously hilited item, if it wasn't 0.
 213                 if (target != fLastMouseEventTarget) {
 214                     if (fLastMouseEventTarget != null) {
 215                         LWToolkit.postEvent(new MouseEvent(fLastMouseEventTarget, MouseEvent.MOUSE_EXITED, when, modifiers, x - fLastTargetRect.x, y - fLastTargetRect.y, 0, false));
 216                     }
 217                     // Send a mouseEntered to the current hilited item, if it wasn't 0.
 218                     if (target != null) {
 219                         LWToolkit.postEvent(new MouseEvent(target, MouseEvent.MOUSE_ENTERED, when, modifiers, x - targetRect.x, y - targetRect.y, 0, false));
 220                     }
 221                     fLastMouseEventTarget = target;
 222                     fLastTargetRect = targetRect;
 223                 }
 224                 // Post a mouse event to the current item.
 225                 if (target == null) return;
 226                 LWToolkit.postEvent(new MouseEvent(target, kind, when, modifiers, x - targetRect.x, y - targetRect.y, 0, false));
 227             }
 228         });
 229     }
 230 
 231     @Override
 232     public void addNotify() {
 233         synchronized (getTreeLock()) {
 234             super.addNotify();
 235             if (fModelPtr == 0) {
 236                 fInvoker.addContainerListener(this);
 237                 fInvoker.addComponentListener(this);
 238                 fPropertyListener = new ScreenMenuPropertyListener(this);
 239                 fInvoker.addPropertyChangeListener(fPropertyListener);
 240 
 241                 final Icon icon = fInvoker.getIcon();
 242                 if (icon != null) {
 243                     setIcon(icon);
 244                 }
 245 
 246                 final String tooltipText = fInvoker.getToolTipText();
 247                 if (tooltipText != null) {
 248                     setToolTipText(tooltipText);
 249                 }
 250                 final MenuComponentPeer peer = getPeer();
 251                 if (peer instanceof CMenu) {
 252                     final CMenu menu = (CMenu) peer;
 253                     final long nativeMenu = menu.getNativeMenu();
 254                     fModelPtr = addMenuListeners(this, nativeMenu);
 255                 }
 256             }
 257         }
 258     }
 259 
 260     @Override
 261     public void removeNotify() {
 262         synchronized (getTreeLock()) {
 263             // Call super so that the NSMenu has been removed, before we release
 264             // the delegate in removeMenuListeners
 265             super.removeNotify();
 266             fItems.clear();
 267             if (fModelPtr != 0) {
 268                 removeMenuListeners(fModelPtr);
 269                 fModelPtr = 0;
 270                 fInvoker.removeContainerListener(this);
 271                 fInvoker.removeComponentListener(this);
 272                 fInvoker.removePropertyChangeListener(fPropertyListener);
 273             }
 274         }
 275     }
 276 
 277     /**
 278      * Invoked when a component has been added to the container.
 279      */
 280     @Override
 281     public void componentAdded(final ContainerEvent e) {
 282         addItem(e.getChild());
 283     }
 284 
 285     /**
 286      * Invoked when a component has been removed from the container.
 287      */
 288     @Override
 289     public void componentRemoved(final ContainerEvent e) {
 290         final Component child = e.getChild();
 291         final MenuItem sm = fItems.get(child);
 292         if (sm == null) return;
 293 
 294         remove(sm);
 295         fItems.remove(sm);
 296     }
 297 
 298     /**
 299      * Invoked when the component's size changes.
 300      */
 301     @Override
 302     public void componentResized(final ComponentEvent e) {}
 303 
 304     /**
 305      * Invoked when the component's position changes.
 306      */
 307     @Override
 308     public void componentMoved(final ComponentEvent e) {}
 309 
 310     /**
 311      * Invoked when the component has been made visible.
 312      * See componentHidden - we should still have a MenuItem
 313      * it just isn't inserted
 314      */
 315     @Override
 316     public void componentShown(final ComponentEvent e) {
 317         setVisible(true);
 318     }
 319 
 320     /**
 321      * Invoked when the component has been made invisible.
 322      * MenuComponent.setVisible does nothing,
 323      * so we remove the ScreenMenuItem from the ScreenMenu
 324      * but leave it in fItems
 325      */
 326     @Override
 327     public void componentHidden(final ComponentEvent e) {
 328         setVisible(false);
 329     }
 330 
 331     private void setVisible(final boolean b) {
 332         // Tell our parent to add/remove us
 333         final MenuContainer parent = getParent();
 334 
 335         if (parent != null) {
 336             if (parent instanceof ScreenMenu) {
 337                 final ScreenMenu sm = (ScreenMenu)parent;
 338                 sm.setChildVisible(fInvoker, b);
 339             }
 340         }
 341     }
 342 
 343     @Override
 344     public void setChildVisible(final JMenuItem child, final boolean b) {
 345         fItems.remove(child);
 346         updateItems();
 347     }
 348 
 349     @Override
 350     public void setAccelerator(final KeyStroke ks) {}
 351 
 352     // only check and radio items can be indeterminate
 353     @Override
 354     public void setIndeterminate(boolean indeterminate) { }
 355 
 356     @Override
 357     public void setToolTipText(final String text) {
 358         final MenuComponentPeer peer = getPeer();
 359         if (!(peer instanceof CMenuItem)) return;
 360 
 361         final CMenuItem cmi = (CMenuItem)peer;
 362         cmi.setToolTipText(text);
 363     }
 364 
 365     @Override
 366     public void setIcon(final Icon i) {
 367         final MenuComponentPeer peer = getPeer();
 368         if (!(peer instanceof CMenuItem)) return;
 369 
 370         final CMenuItem cmi = (CMenuItem)peer;
 371         Image img = null;
 372 
 373         if (i != null) {
 374             if (i.getIconWidth() > 0 && i.getIconHeight() > 0) {
 375                 img = AquaIcon.getImageForIcon(i);
 376             }
 377         }
 378         cmi.setImage(img);
 379     }
 380 
 381 
 382     /**
 383      * Gets a hashCode for a JMenu or JMenuItem or subclass so that we can compare for
 384      * changes in the Menu.
 385      */
 386     private static int getHashCode(final Component m) {
 387         int hashCode = m.hashCode();
 388 
 389         if (m instanceof JMenuItem) {
 390             final JMenuItem mi = (JMenuItem) m;
 391 
 392             final String text = mi.getText();
 393             if (text != null) hashCode ^= text.hashCode();
 394 
 395             final Icon icon = mi.getIcon();
 396             if (icon != null) hashCode ^= icon.hashCode();
 397 
 398             final Icon disabledIcon = mi.getDisabledIcon();
 399             if (disabledIcon != null) hashCode ^= disabledIcon.hashCode();
 400 
 401             final Action action = mi.getAction();
 402             if (action != null) hashCode ^= action.hashCode();
 403 
 404             final KeyStroke ks = mi.getAccelerator();
 405             if (ks != null) hashCode ^= ks.hashCode();
 406 
 407             hashCode ^= Boolean.valueOf(mi.isVisible()).hashCode();
 408             hashCode ^= Boolean.valueOf(mi.isEnabled()).hashCode();
 409             hashCode ^= Boolean.valueOf(mi.isSelected()).hashCode();
 410 
 411         } else if (m instanceof JSeparator) {
 412             hashCode ^= "-".hashCode();
 413         }
 414 
 415         return hashCode;
 416     }
 417 
 418     private void addItem(final Component m) {
 419         if (!m.isVisible()) return;
 420         MenuItem sm = fItems.get(m);
 421 
 422         if (sm == null) {
 423             if (m instanceof JMenu) {
 424                 sm = new ScreenMenu((JMenu)m);
 425             } else if (m instanceof JCheckBoxMenuItem) {
 426                 sm = new ScreenMenuItemCheckbox((JCheckBoxMenuItem)m);
 427             } else if (m instanceof JRadioButtonMenuItem) {
 428                 sm = new ScreenMenuItemCheckbox((JRadioButtonMenuItem)m);
 429             } else if (m instanceof JMenuItem) {
 430                 sm = new ScreenMenuItem((JMenuItem)m);
 431             } else if (m instanceof JPopupMenu.Separator || m instanceof JSeparator) {
 432                 sm = new MenuItem("-"); // This is what java.awt.Menu.addSeparator does
 433             }
 434 
 435             // Only place the menu item in the hashtable if we just created it.
 436             if (sm != null) {
 437                 fItems.put(m, sm);
 438             }
 439         }
 440 
 441         if (sm != null) {
 442             add(sm);
 443         }
 444     }
 445 }