Search code examples
eclipseeclipse-rcprcp

Eclipse: How to get the MenuManager for a specific menu id defined in plugin.xml


I have a standalone eclipse RCP application. The main interaction happens through the main toolbar. Here is the relevant snippet from plugin.xml:

<extension
     point="org.eclipse.ui.menus">
  <menuContribution
        allPopups="false"
        locationURI="toolbar:org.eclipse.ui.main.toolbar">
     <toolbar
           id="my.toolbar.id">
        ...
        <command
              commandId="my.command.id"
              id="my.connect.id"
              label="Connect"
              style="pulldown">
        </command>
        ...
     </toolbar>
  </menuContribution>
  <menuContribution
        allPopups="false"
        locationURI="menu:my.connect.id">
  </menuContribution>

I would like to populate the pulldown menu my.connect.id when it is about to be shown, which can hold different items every time it is opened. It can be done using the MenuManager for this id and add a IMenuListener.

How to obtain the instance of the MenuManager for the given id from plugin.xml?

Thanks a lot.

PS: It is still e3.


Solution

  • I took me a couple of days and research to figure this out. Here is the answer to my own question:

    Give the menu a dyanmic contribution with a class that handles all the contributions.

    plugin.xml:

      <menuContribution
            allPopups="false"
            locationURI="menu:my.connect.id">
         <dynamic
               class="my.ConnectMenu"
               id="my.connect.menu">
         </dynamic>
      </menuContribution>
    

    ConnectMenu.java:

    public class ConnectMenu extends ContributionItem {
    
        private IMenuListener menuListener = new IMenuListener() {
            public void menuAboutToShow(IMenuManager manager) {
                fillMenu(manager);
            }
        };
    
        public ConnectMenu() {
            this("my.connect.menu");
        }
    
        public ConnectMenu(String id) {
            super(id);
        }
    
        @Override
        public void fill(Menu menu, int index) {
            super.fill(menu, index);
    
            if (getParent() instanceof MenuManager) {
                ((MenuManager) getParent()).setRemoveAllWhenShown(true);
                ((MenuManager) getParent()).addMenuListener(menuListener);
            }
        }
    
        private void fillMenu(IMenuManager mgr) {
            mgr.add(createContributionItem());      
    
            mgr.update();
        }
    
        private IContributionItem createContributionItem() {
            // ...
        }
    }
    

    Hope this helps.

    Very helpful to me: https://phisymmetry.wordpress.com/2010/01/03/eclipse-tips-how-to-create-menu-items-dynamically/