Search code examples
eclipseeclipse-plugineclipse-rcp

Eclipse Plugin - Make a menu Item visible only when a particular element is selected


What I want is to add a menu item to Package Explorer and the Project Explorer of Eclipse which is visible only when I right click on a project Element.

What I have done so far is- Added a menu item to both Package and Project Explorer, but they visible on a right click from anywhere.

What I want is the command to only appear if the Project Element is Right Clicked from the project/package explorer.

I don't want the menu item to be visible if someone right clicks on the Package or any folder in any project.

Ie.

Right Click on Project -> Menu Item Visible
Right Click on any other resource in the project -> Menu Item not present

Is this possible by adding attributes ? I am confused as to how to use it. Do I need to add a click listener for the the Package and Project Explorers ?

I am writing this plugin for Eclipse Indigo.


Solution

  • You use the visibleWhen element of the command in the org.eclipse.ui.menus extension point to control visibility.

    For a project you need to check if the current selection adapts to the IProject interface:

    <visibleWhen
           checkEnabled="false">
       <iterate>
          <adapt
              type="org.eclipse.core.resources.IProject">
          </adapt>
       </iterate>
    </visibleWhen>
    

    Which is iterating through the objects in the current selection.

    The selected objects will be some user interface object belonging to the current view, usually these do not directly implement the IProject interface. Instead it may be possible to 'adapt' the object to the interface using the Eclipse adapter manager (see the IAdapterManager, IAdapterFactory, IAdaptable interfaces). The adapt element is testing if the selection object can be adapted.