1 /*
   2  * Copyright (c) 1995, 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 package java.awt;
  26 
  27 import java.io.IOException;
  28 import java.io.ObjectInputStream;
  29 import java.util.Vector;
  30 import java.util.Enumeration;
  31 import sun.awt.AWTAccessor;
  32 import java.awt.peer.MenuBarPeer;
  33 import java.awt.event.KeyEvent;
  34 import javax.accessibility.*;
  35 
  36 /**
  37  * The <code>MenuBar</code> class encapsulates the platform's
  38  * concept of a menu bar bound to a frame. In order to associate
  39  * the menu bar with a <code>Frame</code> object, call the
  40  * frame's <code>setMenuBar</code> method.
  41  * <p>
  42  * <A NAME="mbexample"></A><!-- target for cross references -->
  43  * This is what a menu bar might look like:
  44  * <p>
  45  * <img src="doc-files/MenuBar-1.gif"
  46  * alt="Diagram of MenuBar containing 2 menus: Examples and Options.
  47  * Examples menu is expanded showing items: Basic, Simple, Check, and More Examples."
  48  * style="float:center; margin: 7px 10px;">
  49  * <p>
  50  * A menu bar handles keyboard shortcuts for menu items, passing them
  51  * along to its child menus.
  52  * (Keyboard shortcuts, which are optional, provide the user with
  53  * an alternative to the mouse for invoking a menu item and the
  54  * action that is associated with it.)
  55  * Each menu item can maintain an instance of <code>MenuShortcut</code>.
  56  * The <code>MenuBar</code> class defines several methods,
  57  * {@link MenuBar#shortcuts} and
  58  * {@link MenuBar#getShortcutMenuItem}
  59  * that retrieve information about the shortcuts a given
  60  * menu bar is managing.
  61  *
  62  * @author Sami Shaio
  63  * @see        java.awt.Frame
  64  * @see        java.awt.Frame#setMenuBar(java.awt.MenuBar)
  65  * @see        java.awt.Menu
  66  * @see        java.awt.MenuItem
  67  * @see        java.awt.MenuShortcut
  68  * @since      1.0
  69  */
  70 public class MenuBar extends MenuComponent implements MenuContainer, Accessible {
  71 
  72     static {
  73         /* ensure that the necessary native libraries are loaded */
  74         Toolkit.loadLibraries();
  75         if (!GraphicsEnvironment.isHeadless()) {
  76             initIDs();
  77         }
  78         AWTAccessor.setMenuBarAccessor(
  79             new AWTAccessor.MenuBarAccessor() {
  80                 public Menu getHelpMenu(MenuBar menuBar) {
  81                     return menuBar.helpMenu;
  82                 }
  83 
  84                 public Vector<Menu> getMenus(MenuBar menuBar) {
  85                     return menuBar.menus;
  86                 }
  87             });
  88     }
  89 
  90     /**
  91      * This field represents a vector of the
  92      * actual menus that will be part of the MenuBar.
  93      *
  94      * @serial
  95      * @see #countMenus()
  96      */
  97     Vector<Menu> menus = new Vector<>();
  98 
  99     /**
 100      * This menu is a special menu dedicated to
 101      * help.  The one thing to note about this menu
 102      * is that on some platforms it appears at the
 103      * right edge of the menubar.
 104      *
 105      * @serial
 106      * @see #getHelpMenu()
 107      * @see #setHelpMenu(Menu)
 108      */
 109     Menu helpMenu;
 110 
 111     private static final String base = "menubar";
 112     private static int nameCounter = 0;
 113 
 114     /*
 115      * JDK 1.1 serialVersionUID
 116      */
 117      private static final long serialVersionUID = -4930327919388951260L;
 118 
 119     /**
 120      * Creates a new menu bar.
 121      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 122      * returns true.
 123      * @see java.awt.GraphicsEnvironment#isHeadless
 124      */
 125     public MenuBar() throws HeadlessException {
 126     }
 127 
 128     /**
 129      * Construct a name for this MenuComponent.  Called by getName() when
 130      * the name is null.
 131      */
 132     String constructComponentName() {
 133         synchronized (MenuBar.class) {
 134             return base + nameCounter++;
 135         }
 136     }
 137 
 138     /**
 139      * Creates the menu bar's peer.  The peer allows us to change the
 140      * appearance of the menu bar without changing any of the menu bar's
 141      * functionality.
 142      */
 143     public void addNotify() {
 144         synchronized (getTreeLock()) {
 145             if (peer == null)
 146                 peer = Toolkit.getDefaultToolkit().createMenuBar(this);
 147 
 148             int nmenus = getMenuCount();
 149             for (int i = 0 ; i < nmenus ; i++) {
 150                 getMenu(i).addNotify();
 151             }
 152         }
 153     }
 154 
 155     /**
 156      * Removes the menu bar's peer.  The peer allows us to change the
 157      * appearance of the menu bar without changing any of the menu bar's
 158      * functionality.
 159      */
 160     public void removeNotify() {
 161         synchronized (getTreeLock()) {
 162             int nmenus = getMenuCount();
 163             for (int i = 0 ; i < nmenus ; i++) {
 164                 getMenu(i).removeNotify();
 165             }
 166             super.removeNotify();
 167         }
 168     }
 169 
 170     /**
 171      * Gets the help menu on the menu bar.
 172      * @return    the help menu on this menu bar.
 173      */
 174     public Menu getHelpMenu() {
 175         return helpMenu;
 176     }
 177 
 178     /**
 179      * Sets the specified menu to be this menu bar's help menu.
 180      * If this menu bar has an existing help menu, the old help menu is
 181      * removed from the menu bar, and replaced with the specified menu.
 182      * @param m    the menu to be set as the help menu
 183      */
 184     public void setHelpMenu(Menu m) {
 185         synchronized (getTreeLock()) {
 186             if (helpMenu == m) {
 187                 return;
 188             }
 189             if (helpMenu != null) {
 190                 remove(helpMenu);
 191             }
 192             if (m.parent != this) {
 193                 add(m);
 194             }
 195             helpMenu = m;
 196             if (m != null) {
 197                 m.isHelpMenu = true;
 198                 m.parent = this;
 199                 MenuBarPeer peer = (MenuBarPeer)this.peer;
 200                 if (peer != null) {
 201                     if (m.peer == null) {
 202                         m.addNotify();
 203                     }
 204                     peer.addHelpMenu(m);
 205                 }
 206             }
 207         }
 208     }
 209 
 210     /**
 211      * Adds the specified menu to the menu bar.
 212      * If the menu has been part of another menu bar,
 213      * removes it from that menu bar.
 214      *
 215      * @param        m   the menu to be added
 216      * @return       the menu added
 217      * @see          java.awt.MenuBar#remove(int)
 218      * @see          java.awt.MenuBar#remove(java.awt.MenuComponent)
 219      */
 220     public Menu add(Menu m) {
 221         synchronized (getTreeLock()) {
 222             if (m.parent != null) {
 223                 m.parent.remove(m);
 224             }
 225             menus.addElement(m);
 226             m.parent = this;
 227 
 228             MenuBarPeer peer = (MenuBarPeer)this.peer;
 229             if (peer != null) {
 230                 if (m.peer == null) {
 231                     m.addNotify();
 232                 }
 233                 peer.addMenu(m);
 234             }
 235             return m;
 236         }
 237     }
 238 
 239     /**
 240      * Removes the menu located at the specified
 241      * index from this menu bar.
 242      * @param        index   the position of the menu to be removed.
 243      * @see          java.awt.MenuBar#add(java.awt.Menu)
 244      */
 245     public void remove(int index) {
 246         synchronized (getTreeLock()) {
 247             Menu m = getMenu(index);
 248             menus.removeElementAt(index);
 249             MenuBarPeer peer = (MenuBarPeer)this.peer;
 250             if (peer != null) {
 251                 m.removeNotify();
 252                 m.parent = null;
 253                 peer.delMenu(index);
 254             }
 255         }
 256     }
 257 
 258     /**
 259      * Removes the specified menu component from this menu bar.
 260      * @param        m the menu component to be removed.
 261      * @see          java.awt.MenuBar#add(java.awt.Menu)
 262      */
 263     public void remove(MenuComponent m) {
 264         synchronized (getTreeLock()) {
 265             int index = menus.indexOf(m);
 266             if (index >= 0) {
 267                 remove(index);
 268             }
 269         }
 270     }
 271 
 272     /**
 273      * Gets the number of menus on the menu bar.
 274      * @return     the number of menus on the menu bar.
 275      * @since      1.1
 276      */
 277     public int getMenuCount() {
 278         return countMenus();
 279     }
 280 
 281     /**
 282      * Gets the number of menus on the menu bar.
 283      *
 284      * @return the number of menus on the menu bar.
 285      * @deprecated As of JDK version 1.1,
 286      * replaced by <code>getMenuCount()</code>.
 287      */
 288     @Deprecated
 289     public int countMenus() {
 290         return getMenuCountImpl();
 291     }
 292 
 293     /*
 294      * This is called by the native code, so client code can't
 295      * be called on the toolkit thread.
 296      */
 297     final int getMenuCountImpl() {
 298         return menus.size();
 299     }
 300 
 301     /**
 302      * Gets the specified menu.
 303      * @param      i the index position of the menu to be returned.
 304      * @return     the menu at the specified index of this menu bar.
 305      */
 306     public Menu getMenu(int i) {
 307         return getMenuImpl(i);
 308     }
 309 
 310     /*
 311      * This is called by the native code, so client code can't
 312      * be called on the toolkit thread.
 313      */
 314     final Menu getMenuImpl(int i) {
 315         return menus.elementAt(i);
 316     }
 317 
 318     /**
 319      * Gets an enumeration of all menu shortcuts this menu bar
 320      * is managing.
 321      * @return      an enumeration of menu shortcuts that this
 322      *                      menu bar is managing.
 323      * @see         java.awt.MenuShortcut
 324      * @since       1.1
 325      */
 326     public synchronized Enumeration<MenuShortcut> shortcuts() {
 327         Vector<MenuShortcut> shortcuts = new Vector<>();
 328         int nmenus = getMenuCount();
 329         for (int i = 0 ; i < nmenus ; i++) {
 330             Enumeration<MenuShortcut> e = getMenu(i).shortcuts();
 331             while (e.hasMoreElements()) {
 332                 shortcuts.addElement(e.nextElement());
 333             }
 334         }
 335         return shortcuts.elements();
 336     }
 337 
 338     /**
 339      * Gets the instance of <code>MenuItem</code> associated
 340      * with the specified <code>MenuShortcut</code> object,
 341      * or <code>null</code> if none of the menu items being managed
 342      * by this menu bar is associated with the specified menu
 343      * shortcut.
 344      * @param  s the specified menu shortcut.
 345      * @return the menu item for the specified shortcut.
 346      * @see java.awt.MenuItem
 347      * @see java.awt.MenuShortcut
 348      * @since 1.1
 349      */
 350      public MenuItem getShortcutMenuItem(MenuShortcut s) {
 351         int nmenus = getMenuCount();
 352         for (int i = 0 ; i < nmenus ; i++) {
 353             MenuItem mi = getMenu(i).getShortcutMenuItem(s);
 354             if (mi != null) {
 355                 return mi;
 356             }
 357         }
 358         return null;  // MenuShortcut wasn't found
 359      }
 360 
 361     /*
 362      * Post an ACTION_EVENT to the target of the MenuPeer
 363      * associated with the specified keyboard event (on
 364      * keydown).  Returns true if there is an associated
 365      * keyboard event.
 366      */
 367     boolean handleShortcut(KeyEvent e) {
 368         // Is it a key event?
 369         int id = e.getID();
 370         if (id != KeyEvent.KEY_PRESSED && id != KeyEvent.KEY_RELEASED) {
 371             return false;
 372         }
 373 
 374         // Is the accelerator modifier key pressed?
 375         int accelKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
 376         if ((e.getModifiers() & accelKey) == 0) {
 377             return false;
 378         }
 379 
 380         // Pass MenuShortcut on to child menus.
 381         int nmenus = getMenuCount();
 382         for (int i = 0 ; i < nmenus ; i++) {
 383             Menu m = getMenu(i);
 384             if (m.handleShortcut(e)) {
 385                 return true;
 386             }
 387         }
 388         return false;
 389     }
 390 
 391     /**
 392      * Deletes the specified menu shortcut.
 393      * @param     s the menu shortcut to delete.
 394      * @since     1.1
 395      */
 396     public void deleteShortcut(MenuShortcut s) {
 397         int nmenus = getMenuCount();
 398         for (int i = 0 ; i < nmenus ; i++) {
 399             getMenu(i).deleteShortcut(s);
 400         }
 401     }
 402 
 403     /* Serialization support.  Restore the (transient) parent
 404      * fields of Menubar menus here.
 405      */
 406 
 407     /**
 408      * The MenuBar's serialized data version.
 409      *
 410      * @serial
 411      */
 412     private int menuBarSerializedDataVersion = 1;
 413 
 414     /**
 415      * Writes default serializable fields to stream.
 416      *
 417      * @param s the <code>ObjectOutputStream</code> to write
 418      * @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
 419      * @see #readObject(java.io.ObjectInputStream)
 420      */
 421     private void writeObject(java.io.ObjectOutputStream s)
 422       throws java.lang.ClassNotFoundException,
 423              java.io.IOException
 424     {
 425       s.defaultWriteObject();
 426     }
 427 
 428     /**
 429      * Reads the <code>ObjectInputStream</code>.
 430      * Unrecognized keys or values will be ignored.
 431      *
 432      * @param s the <code>ObjectInputStream</code> to read
 433      * @exception HeadlessException if
 434      *   <code>GraphicsEnvironment.isHeadless</code> returns
 435      *   <code>true</code>
 436      * @see java.awt.GraphicsEnvironment#isHeadless
 437      * @see #writeObject(java.io.ObjectOutputStream)
 438      */
 439     private void readObject(ObjectInputStream s)
 440       throws ClassNotFoundException, IOException, HeadlessException
 441     {
 442       // HeadlessException will be thrown from MenuComponent's readObject
 443       s.defaultReadObject();
 444       for (int i = 0; i < menus.size(); i++) {
 445         Menu m = menus.elementAt(i);
 446         m.parent = this;
 447       }
 448     }
 449 
 450     /**
 451      * Initialize JNI field and method IDs
 452      */
 453     private static native void initIDs();
 454 
 455 
 456 /////////////////
 457 // Accessibility support
 458 ////////////////
 459 
 460     /**
 461      * Gets the AccessibleContext associated with this MenuBar.
 462      * For menu bars, the AccessibleContext takes the form of an
 463      * AccessibleAWTMenuBar.
 464      * A new AccessibleAWTMenuBar instance is created if necessary.
 465      *
 466      * @return an AccessibleAWTMenuBar that serves as the
 467      *         AccessibleContext of this MenuBar
 468      * @since 1.3
 469      */
 470     public AccessibleContext getAccessibleContext() {
 471         if (accessibleContext == null) {
 472             accessibleContext = new AccessibleAWTMenuBar();
 473         }
 474         return accessibleContext;
 475     }
 476 
 477     /**
 478      * Defined in MenuComponent. Overridden here.
 479      */
 480     int getAccessibleChildIndex(MenuComponent child) {
 481         return menus.indexOf(child);
 482     }
 483 
 484     /**
 485      * Inner class of MenuBar used to provide default support for
 486      * accessibility.  This class is not meant to be used directly by
 487      * application developers, but is instead meant only to be
 488      * subclassed by menu component developers.
 489      * <p>
 490      * This class implements accessibility support for the
 491      * <code>MenuBar</code> class.  It provides an implementation of the
 492      * Java Accessibility API appropriate to menu bar user-interface elements.
 493      * @since 1.3
 494      */
 495     protected class AccessibleAWTMenuBar extends AccessibleAWTMenuComponent
 496     {
 497         /*
 498          * JDK 1.3 serialVersionUID
 499          */
 500         private static final long serialVersionUID = -8577604491830083815L;
 501 
 502         /**
 503          * Get the role of this object.
 504          *
 505          * @return an instance of AccessibleRole describing the role of the
 506          * object
 507          * @since 1.4
 508          */
 509         public AccessibleRole getAccessibleRole() {
 510             return AccessibleRole.MENU_BAR;
 511         }
 512 
 513     } // class AccessibleAWTMenuBar
 514 
 515 }