Eclipse menus and unwanted contribution items

I have just faced a problem with Eclipse menus.
Because I did not find a simple solution, I had to use mine and I decided to share it here.
It is not elegant, but it works.

The problem

I have created a multipage editor. And one of the pages is a simple composite that embeds a ZEST diagram.
And I want to have a contextual menu on this diagram.

So, I registered it on the composite using:

MenuManager menuMgr = new MenuManager() ;
final Menu menu = menuMgr.createContextMenu( this.graphViewer.getGraphControl());
this.graphViewer.getGraphControl().setMenu( menu );
this.eipDesigner.getSite().registerContextMenu( menuMgr, this.graphViewer );

It allows me to register menu items from commands in my plugin.xml (using the org.eclipse.ui.menus extension-point).
Unfortunately, my menu contains items that do not make sense for my editor (Run as, Debug as, Compare with…).
These items are contributed by other plug-ins that I cannot get rid off (they are required).

The solution

After looking at the code that populates the menu from plug-in contributions, I found a light way to filter the displayed items.

MenuManager menuMgr = new MenuManager() {
@Override
public IContributionItem[] getItems() {

  IContributionItem[] items = super.getItems();
  List<IContributionItem> filteredItems = new ArrayList<IContributionItem> ();
  for( IContributionItem item : items ) {
      if( item != null
           && item.getId() != null
           && item.getId().startsWith( "com.ebmwebsourcing." ))
         filteredItems.add( item );
  }

  items = new IContributionItem[ filteredItems.size()];
  return filteredItems.toArray( items );
  }
};

final Menu menu = menuMgr.createContextMenu( this.graphViewer.getGraphControl());
this.graphViewer.getGraphControl().setMenu( menu );
this.eipDesigner.getSite().registerContextMenu( menuMgr, this.graphViewer );

And it works.
I only have to make sure my contributions have a valid ID.


About this entry