Time for action – contributing commands to pop-up menus

It's useful to be able to add contributions to pop-up menus so that they can be used by different places. Fortunately, this can be done fairly easily with the menuContribution element and a combination of enablement tests. This allows the removal of the Action introduced in the first part of this chapter with a more generic command and handler pairing.

There is a deprecated extension point—which still works in Eclipse 4.2 today—called objectContribution, which is a single specialized hook for contributing a pop-up menu to an object. This has been deprecated for some time, but often older tutorials or examples may refer to it.

  1. Open the TimeZoneTableView class and add the hookContextMenu() method as follows:
    private void hookContextMenu(Viewer viewer) {
      MenuManager manager = new MenuManager("#PopupMenu");
      Menu menu = manager.createContextMenu(viewer.getControl());
      viewer.getControl().setMenu(menu);
      getSite().registerContextMenu(manager, viewer);
    }
  2. Add the same hookContextMenu() method to the TimeZoneTreeView class.
  3. In the TimeZoneTreeView class, at the end of the createPartControl() method, call hookContextMenu(tableViewer).
  4. In the TimeZoneTableView class, at the end of the createPartControl() method, replace the call to the action with a call to hookContextMenu() instead:
    hookContextMenu(tableViewer);
    //The following commented lines of code need to be removed
    /*MenuManager manager = new MenuManager("#PopupMenu");
    Menu menu = manager.createContextMenu(tableViewer.getControl());
    tableViewer.getControl().setMenu(menu);
    Action deprecated = new Action() {
      public void run() {
        MessageDialog.openInformation(null, "Hello", "World");
      }
    };
    deprecated.setText("Hello");
    manager.add(deprecated);*/
  5. Running the Eclipse instance now and showing the menu results in nothing being displayed, because no menu items have been added to it yet.
  6. Create a command and a handler Show the Time.
    <extension point="org.eclipse.ui.commands">
      <command name="Show the Time" description="Shows the Time"
        id="com.packtpub.e4.clock.ui.command.showTheTime"/>
    </extension>
    <extension point="org.eclipse.ui.handlers">
      <handler class=
        "com.packtpub.e4.clock.ui.handlers.ShowTheTime"
        commandId="com.packtpub.e4.clock.ui.command.showTheTime"/>
    </extension>
  7. Create a class ShowTheTime, in the com.packtpub.e4.clock.ui.handlers package, which extends org.eclipse.core.commands.AbstractHandler, to show the time in a specific time zone.
    public class ShowTheTime extends AbstractHandler {
      public Object execute(ExecutionEvent event) {
        ISelection sel = HandlerUtil.getActiveWorkbenchWindow(event)
         .getSelectionService().getSelection();
        if (sel instanceof IStructuredSelection && !sel.isEmpty()) {
          Object value =
           ((IStructuredSelection)sel).getFirstElement();
          if (value instanceof TimeZone) {
            SimpleDateFormat sdf = new SimpleDateFormat();
            sdf.setTimeZone((TimeZone) value);
            MessageDialog.openInformation(null, "The time is",
              sdf.format(new Date()));
          } 
        }
        return null;
      }
    }
  8. Finally, to hook it up, a menu needs to be added to the special locationURI popup:org.eclipse.ui.popup.any.
    <extension point="org.eclipse.ui.menus">
      <menuContribution allPopups="false"
       locationURI="popup:org.eclipse.ui.popup.any">
        <command label="Show the Time" style="push"
         commandId="com.packtpub.e4.clock.ui.command.showTheTime">
          <visibleWhen checkEnabled="false">
            <with variable="selection">
              <iterate ifEmpty="false">
                <adapt type="java.util.TimeZone"/>
              </iterate>
            </with>
          </visibleWhen
        </command>
      </menuContribution>
    </extension>
  9. Run the Eclipse instance, and open the Time Zone Table view or Time Zone Table view. Right-click on a TimeZone, and the command Show the Time will be displayed (that is, one of the leaves of the tree or one of the rows of the table). Select the command and a dialog should show the time.

What just happened?

The views from the previous chapter and the knowledge of how to wire up commands in this chapter provided a unified means of adding commands, based on the selected object type. This approach of registering commands is powerful, because any time a time zone is exposed as a selection in the future it will now have a Show the Time menu added to it automatically.

The commands define a generic operation, and handlers bind those commands to implementations. The context-sensitive menu is provided by the pop-up menu extension point using the locationURI popup:org.eclipse.ui.popup.any. This allows the menu to be added to any pop-up menu that uses a MenuManager and when the selection contains a TimeZone. The MenuManager is responsible for listening to the mouse gestures to show a menu, and filling it with details when it is shown.

In the example, the command was enabled when the object was an instance of a TimeZone, and also if it could be adapted to a TimeZone. This would allow another object type (say, a contact card) to have an adapter to convert it to a TimeZone, and thus show the time in that contact's location.

Have a go hero – using view menus and toolbars

The way to add a view menu is similar to adding a pop-up menu; the locationURI used is the view's ID rather than the menu item itself. Add a Show the Time menu to the TimeZone view as a view menu.

Another way of adding the menu is to add it as a toolbar, which is an icon in the main Eclipse window. Add the Show the Time icon by adding it to the global toolbar instead.

To facilitate testing of views, add a menu item that allows you to show the TimeZone views with PlatformUI.getActiveWorkbenchWindow().getActivePage().showView(id).

Pop quiz – understanding menus

Q1. What's the difference between an Action and a Command, and which one should be used?

Q2. How can a Command be connected to a menu?

Q3. What is the M1 key?

Q4. How are keystrokes bound to commands?

Q5. What is a menu locationURI?

Q6. How is a pop-up menu created?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset