コード例 #1
0
  /**
   * Locate an action (a menu item, actually) with the given id in the current menu bar and run it.
   *
   * @param actionId the action to find
   * @return true if an action was found, false otherwise
   */
  private boolean runAction(String actionId) {
    MWindow window = app.getSelectedElement();
    if (window == null) {
      return false;
    }
    MMenu topMenu = window.getMainMenu();
    MMenuItem item = findAction(actionId, topMenu);
    if (item == null || !item.isEnabled()) {
      return false;
    }
    try {
      // disable the about and prefs items -- they shouldn't be
      // able to be run when another item is being triggered
      final Display display = Display.getDefault();
      MenuItem aboutItem = null;
      boolean aboutEnabled = true;
      MenuItem prefsItem = null;
      boolean prefsEnabled = true;

      Menu appMenuBar = display.getMenuBar();
      if (appMenuBar != null) {
        aboutItem = findMenuItemById(appMenuBar, SWT.ID_ABOUT);
        if (aboutItem != null) {
          aboutEnabled = aboutItem.getEnabled();
          aboutItem.setEnabled(false);
        }
        prefsItem = findMenuItemById(appMenuBar, SWT.ID_PREFERENCES);
        if (prefsItem != null) {
          prefsEnabled = prefsItem.getEnabled();
          prefsItem.setEnabled(false);
        }
      }
      try {
        simulateMenuSelection(item);
      } finally {
        if (prefsItem != null) {
          prefsItem.setEnabled(prefsEnabled);
        }
        if (aboutItem != null) {
          aboutItem.setEnabled(aboutEnabled);
        }
      }
    } catch (Exception e) {
      // theoretically, one of
      // SecurityException,Illegal*Exception,InvocationTargetException,NoSuch*Exception
      // not expected to happen at all.
      log(e);
      // return false?
    }
    return true;
  }
コード例 #2
0
 private void hookAppMenuItem(int menuItemId, final String commandId) {
   final Display display = Display.getDefault();
   Menu[] menusToCheck = new Menu[] {display.getMenuBar(), display.getSystemMenu()};
   for (Menu topLevelMenu : menusToCheck) {
     if (topLevelMenu == null) {
       continue;
     }
     MenuItem item = findMenuItemById(topLevelMenu, menuItemId);
     if (item != null) {
       item.addSelectionListener(
           new SelectionAdapter() {
             public void widgetSelected(SelectionEvent e) {
               if (runCommand(commandId) || runAction(commandId)) {
                 e.doit = false;
               }
             }
           });
     }
   }
 }