Wednesday, March 10, 2010

Add eclipse-rcp's views short list, perspective short list in the org.eclipse.ui.menus plugin via dynamic CompoundContributionItem class

Recently, I've encountered a problem wherein I wanted to display the eclipse-rcp's list of view, perspective etc using the extension org.eclipse.ui.menus. The problem can easily solved by the ApplicationActionBarAdvisor, see the code below:

private IContributionItem showViewItem;
protected void makeActions(final IWorkbenchWindow window) {
listView = ContributionItemFactory.VIEWS_SHORTLIST.create(window);

protected void fillMenuBar(IMenuManager menuBar) {
MenuManager windowMenu = new MenuManager("&Window", IWorkbenchActionConstants.M_WINDOW);
MenuManager viewManager = new MenuManager("Show View", "showView");

menuBar.add(windowMenu); //adds the Window menu to the horizontal toolbar

Unfortunately, this is not what I want and I want to take advantage of the eclipse-rcp's plugin system. So I ended up peeking into the rcp's core classes and found out a solution:

What to do:
1.) Create a new plugin project, Hello World will do.
2.) Open plugin.xml and in the Extensions tab add org.eclipse.ui.menus
a.) add menuContribution and sets its
b.) right click contribution and select New->menu, change the label=File
c.) right click File menu and select New->menu, change the label=Show View
d.) right click Show View menu and select New->dynamic
d.i) select dynamic and right click class*, name the class and select CompoundContributionItem as its super class
d.ii) example: public class ListView extends CompoundContributionItem { }
3.) Now all we have to do is override the CompoundContributionItem's getContributionItems method, like this:

protected IContributionItem[] getContributionItems() {
List menuContributionList = new ArrayList();
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IContributionItem item = ContributionItemFactory.VIEWS_SHORTLIST.create(window);
menuContributionList.add(item); //add the list of views in the menu
return menuContributionList.toArray(new IContributionItem[menuContributionList.size()]);


Anonymous said...

Thanks you very much, I also encounter this problem, and it take a long time ti solve, after read you post, I can solve it now, it's great solution