ScreenMenu.java 15.2 KB
Newer Older
1
/*
2
 * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package com.apple.laf;

import java.awt.*;
import java.awt.event.*;
import java.awt.peer.MenuComponentPeer;
import java.util.Hashtable;

import javax.swing.*;

35
import sun.awt.SunToolkit;
36 37 38
import sun.lwawt.LWToolkit;
import sun.lwawt.macosx.*;

S
serb 已提交
39 40 41 42
final class ScreenMenu extends Menu
        implements ContainerListener, ComponentListener,
                   ScreenMenuPropertyHandler {

43
    static {
44 45 46 47 48 49 50
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<Void>() {
                public Void run() {
                    System.loadLibrary("awt");
                    return null;
                }
            });
51 52 53
    }

    // screen menu stuff
S
serb 已提交
54 55
    private static native long addMenuListeners(ScreenMenu listener, long nativeMenu);
    private static native void removeMenuListeners(long modelPtr);
56

S
serb 已提交
57
    private transient long fModelPtr;
58

S
serb 已提交
59 60
    private final Hashtable<Component, MenuItem> fItems;
    private final JMenu fInvoker;
61

S
serb 已提交
62 63
    private Component fLastMouseEventTarget;
    private Rectangle fLastTargetRect;
64 65
    private volatile Rectangle[] fItemBounds;

S
serb 已提交
66 67
    private ScreenMenuPropertyListener fPropertyListener;

68
    // Array of child hashes used to see if we need to recreate the Menu.
S
serb 已提交
69
    private int childHashArray[];
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

    ScreenMenu(final JMenu invoker) {
        super(invoker.getText());
        fInvoker = invoker;

        int count = fInvoker.getMenuComponentCount();
        if (count < 5) count = 5;
        fItems = new Hashtable<Component, MenuItem>(count);
        setEnabled(fInvoker.isEnabled());
        updateItems();
    }

    /**
     * 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
     * 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
     * way, such as the number of menu items, the text of the menuitems, icon, shortcut etc.
     */
S
serb 已提交
87
    private static boolean needsUpdate(final Component items[], final int childHashArray[]) {
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
      if (items == null || childHashArray == null) {
        return true;
      }
      if (childHashArray.length != items.length) {
       return true;
      }
      for (int i = 0; i < items.length; i++) {
          final int hashCode = getHashCode(items[i]);
          if (hashCode != childHashArray[i]) {
            return true;
          }
      }
      return false;
    }

    /**
     * Used to recreate the AWT based Menu structure that implements the Screen Menu.
     * Also computes hashcode and stores them so that we can compare them later in needsUpdate.
     */
S
serb 已提交
107
    private void updateItems() {
108 109 110 111
        final int count = fInvoker.getMenuComponentCount();
        final Component[] items = fInvoker.getMenuComponents();
        if (needsUpdate(items, childHashArray)) {
            removeAll();
112
            fItems.clear();
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
            if (count <= 0) return;

            childHashArray = new int[count];
            for (int i = 0; i < count; i++) {
                addItem(items[i]);
                childHashArray[i] = getHashCode(items[i]);
            }
        }
    }

    /**
     * Callback from JavaMenuUpdater.m -- called when menu first opens
     */
    public void invokeOpenLater() {
        final JMenu invoker = fInvoker;
        if (invoker == null) {
            System.err.println("invoker is null!");
            return;
        }

        try {
            LWCToolkit.invokeAndWait(new Runnable() {
                public void run() {
                    invoker.setSelected(true);
                    invoker.validate();
                    updateItems();
                    fItemBounds = new Rectangle[invoker.getMenuComponentCount()];
                }
141
            }, invoker);
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        } catch (final Exception e) {
            System.err.println(e);
            e.printStackTrace();
        }
    }

    /**
     * Callback from JavaMenuUpdater.m -- called when menu closes.
     */
    public void invokeMenuClosing() {
        final JMenu invoker = fInvoker;
        if (invoker == null) return;

        try {
            LWCToolkit.invokeAndWait(new Runnable() {
                public void run() {
                    invoker.setSelected(false);
S
serb 已提交
159
                    // Null out the tracking rectangles and the array.
160
                    if (fItemBounds != null) {
S
serb 已提交
161 162 163
                        for (int i = 0; i < fItemBounds.length; i++) {
                            fItemBounds[i] = null;
                        }
164
                    }
S
serb 已提交
165 166
                    fItemBounds = null;
                }
167
            }, invoker);
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Callback from JavaMenuUpdater.m -- called when menu item is hilighted.
     *
     * @param inWhichItem The menu item selected by the user. -1 if mouse moves off the menu.
     * @param itemRectTop
     * @param itemRectLeft
     * @param itemRectBottom
     * @param itemRectRight Tracking rectangle coordinates.
     */
    public void handleItemTargeted(final int inWhichItem, final int itemRectTop, final int itemRectLeft, final int itemRectBottom, final int itemRectRight) {
        if (fItemBounds == null || inWhichItem < 0 || inWhichItem > (fItemBounds.length - 1)) return;
        final Rectangle itemRect = new Rectangle(itemRectLeft, itemRectTop, itemRectRight - itemRectLeft, itemRectBottom - itemRectTop);
        fItemBounds[inWhichItem] = itemRect;
    }

    /**
     * Callback from JavaMenuUpdater.m -- called when mouse event happens on the menu.
     */
    public void handleMouseEvent(final int kind, final int x, final int y, final int modifiers, final long when) {
        if (kind == 0) return;
        if (fItemBounds == null) return;

195
        SunToolkit.executeOnEventHandlerThread(fInvoker, new Runnable() {
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
            @Override
            public void run() {
                Component target = null;
                Rectangle targetRect = null;
                for (int i = 0; i < fItemBounds.length; i++) {
                    final Rectangle testRect = fItemBounds[i];
                    if (testRect != null) {
                        if (testRect.contains(x, y)) {
                            target = fInvoker.getMenuComponent(i);
                            targetRect = testRect;
                            break;
                        }
                    }
                }
                if (target == null && fLastMouseEventTarget == null) return;

                // Send a mouseExited to the previously hilited item, if it wasn't 0.
                if (target != fLastMouseEventTarget) {
                    if (fLastMouseEventTarget != null) {
                        LWToolkit.postEvent(new MouseEvent(fLastMouseEventTarget, MouseEvent.MOUSE_EXITED, when, modifiers, x - fLastTargetRect.x, y - fLastTargetRect.y, 0, false));
                    }
                    // Send a mouseEntered to the current hilited item, if it wasn't 0.
                    if (target != null) {
                        LWToolkit.postEvent(new MouseEvent(target, MouseEvent.MOUSE_ENTERED, when, modifiers, x - targetRect.x, y - targetRect.y, 0, false));
                    }
                    fLastMouseEventTarget = target;
                    fLastTargetRect = targetRect;
                }
                // Post a mouse event to the current item.
                if (target == null) return;
                LWToolkit.postEvent(new MouseEvent(target, kind, when, modifiers, x - targetRect.x, y - targetRect.y, 0, false));
            }
        });
    }

S
serb 已提交
231
    @Override
232
    public void addNotify() {
S
serb 已提交
233 234 235
        synchronized (getTreeLock()) {
            super.addNotify();
            if (fModelPtr == 0) {
236
                fInvoker.getPopupMenu().addContainerListener(this);
S
serb 已提交
237 238 239 240 241 242 243 244
                fInvoker.addComponentListener(this);
                fPropertyListener = new ScreenMenuPropertyListener(this);
                fInvoker.addPropertyChangeListener(fPropertyListener);

                final Icon icon = fInvoker.getIcon();
                if (icon != null) {
                    setIcon(icon);
                }
245

S
serb 已提交
246 247 248 249 250 251 252 253 254 255
                final String tooltipText = fInvoker.getToolTipText();
                if (tooltipText != null) {
                    setToolTipText(tooltipText);
                }
                final MenuComponentPeer peer = getPeer();
                if (peer instanceof CMenu) {
                    final CMenu menu = (CMenu) peer;
                    final long nativeMenu = menu.getNativeMenu();
                    fModelPtr = addMenuListeners(this, nativeMenu);
                }
256 257 258 259
            }
        }
    }

S
serb 已提交
260
    @Override
261
    public void removeNotify() {
S
serb 已提交
262 263 264 265 266 267 268 269
        synchronized (getTreeLock()) {
            // Call super so that the NSMenu has been removed, before we release
            // the delegate in removeMenuListeners
            super.removeNotify();
            fItems.clear();
            if (fModelPtr != 0) {
                removeMenuListeners(fModelPtr);
                fModelPtr = 0;
270
                fInvoker.getPopupMenu().removeContainerListener(this);
S
serb 已提交
271 272 273
                fInvoker.removeComponentListener(this);
                fInvoker.removePropertyChangeListener(fPropertyListener);
            }
274 275 276 277 278 279
        }
    }

    /**
     * Invoked when a component has been added to the container.
     */
S
serb 已提交
280
    @Override
281 282 283 284 285 286 287
    public void componentAdded(final ContainerEvent e) {
        addItem(e.getChild());
    }

    /**
     * Invoked when a component has been removed from the container.
     */
S
serb 已提交
288
    @Override
289 290
    public void componentRemoved(final ContainerEvent e) {
        final Component child = e.getChild();
291
        final MenuItem sm = fItems.remove(child);
292 293
        if (sm == null) return;

S
serb 已提交
294 295
        remove(sm);
    }
296 297 298 299

    /**
     * Invoked when the component's size changes.
     */
S
serb 已提交
300
    @Override
301 302 303 304 305
    public void componentResized(final ComponentEvent e) {}

    /**
     * Invoked when the component's position changes.
     */
S
serb 已提交
306
    @Override
307 308 309 310 311 312 313
    public void componentMoved(final ComponentEvent e) {}

    /**
     * Invoked when the component has been made visible.
     * See componentHidden - we should still have a MenuItem
     * it just isn't inserted
     */
S
serb 已提交
314
    @Override
315 316 317 318 319 320 321 322 323 324
    public void componentShown(final ComponentEvent e) {
        setVisible(true);
    }

    /**
     * Invoked when the component has been made invisible.
     * MenuComponent.setVisible does nothing,
     * so we remove the ScreenMenuItem from the ScreenMenu
     * but leave it in fItems
     */
S
serb 已提交
325
    @Override
326 327 328 329
    public void componentHidden(final ComponentEvent e) {
        setVisible(false);
    }

S
serb 已提交
330
    private void setVisible(final boolean b) {
331 332 333 334 335 336 337
        // Tell our parent to add/remove us
        final MenuContainer parent = getParent();

        if (parent != null) {
            if (parent instanceof ScreenMenu) {
                final ScreenMenu sm = (ScreenMenu)parent;
                sm.setChildVisible(fInvoker, b);
S
serb 已提交
338
            }
339 340 341
        }
    }

S
serb 已提交
342
    @Override
343 344 345 346 347
    public void setChildVisible(final JMenuItem child, final boolean b) {
        fItems.remove(child);
        updateItems();
    }

S
serb 已提交
348
    @Override
349 350 351
    public void setAccelerator(final KeyStroke ks) {}

    // only check and radio items can be indeterminate
S
serb 已提交
352
    @Override
353 354
    public void setIndeterminate(boolean indeterminate) { }

S
serb 已提交
355
    @Override
356 357 358 359 360 361 362 363
    public void setToolTipText(final String text) {
        final MenuComponentPeer peer = getPeer();
        if (!(peer instanceof CMenuItem)) return;

        final CMenuItem cmi = (CMenuItem)peer;
        cmi.setToolTipText(text);
    }

S
serb 已提交
364
    @Override
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    public void setIcon(final Icon i) {
        final MenuComponentPeer peer = getPeer();
        if (!(peer instanceof CMenuItem)) return;

        final CMenuItem cmi = (CMenuItem)peer;
        Image img = null;

        if (i != null) {
            if (i.getIconWidth() > 0 && i.getIconHeight() > 0) {
                img = AquaIcon.getImageForIcon(i);
            }
        }
        cmi.setImage(img);
    }


    /**
     * Gets a hashCode for a JMenu or JMenuItem or subclass so that we can compare for
     * changes in the Menu.
     */
S
serb 已提交
385
    private static int getHashCode(final Component m) {
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
        int hashCode = m.hashCode();

        if (m instanceof JMenuItem) {
            final JMenuItem mi = (JMenuItem) m;

            final String text = mi.getText();
            if (text != null) hashCode ^= text.hashCode();

            final Icon icon = mi.getIcon();
            if (icon != null) hashCode ^= icon.hashCode();

            final Icon disabledIcon = mi.getDisabledIcon();
            if (disabledIcon != null) hashCode ^= disabledIcon.hashCode();

            final Action action = mi.getAction();
            if (action != null) hashCode ^= action.hashCode();

            final KeyStroke ks = mi.getAccelerator();
            if (ks != null) hashCode ^= ks.hashCode();

            hashCode ^= Boolean.valueOf(mi.isVisible()).hashCode();
            hashCode ^= Boolean.valueOf(mi.isEnabled()).hashCode();
            hashCode ^= Boolean.valueOf(mi.isSelected()).hashCode();

        } else if (m instanceof JSeparator) {
            hashCode ^= "-".hashCode();
        }

        return hashCode;
    }

S
serb 已提交
417
    private void addItem(final Component m) {
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
        if (!m.isVisible()) return;
        MenuItem sm = fItems.get(m);

        if (sm == null) {
            if (m instanceof JMenu) {
                sm = new ScreenMenu((JMenu)m);
            } else if (m instanceof JCheckBoxMenuItem) {
                sm = new ScreenMenuItemCheckbox((JCheckBoxMenuItem)m);
            } else if (m instanceof JRadioButtonMenuItem) {
                sm = new ScreenMenuItemCheckbox((JRadioButtonMenuItem)m);
            } else if (m instanceof JMenuItem) {
                sm = new ScreenMenuItem((JMenuItem)m);
            } else if (m instanceof JPopupMenu.Separator || m instanceof JSeparator) {
                sm = new MenuItem("-"); // This is what java.awt.Menu.addSeparator does
            }

            // Only place the menu item in the hashtable if we just created it.
            if (sm != null) {
                fItems.put(m, sm);
            }
        }

        if (sm != null) {
            add(sm);
        }
    }
}