Search code examples
javaeclipseswteclipse-rcpe4

How to disable or enable a MMenu (not MMenuItem) in an Eclipse E4 application


I have an Eclipse E4 application with a MMenu (in the main menu of the application and in popup menus of different parts) that contains items provided at runtime by a dynamic menu contribution.

What I want to achieve is to disable the menu element, if the menu contribution does not provide any item. Something like @CanExecute for handler classes for commands or direct menu items.


Solution

  • Do you use the latest version of eclipse and you have an Application.e4xmi file?
    If so, for your "Dynamic Menu Contribution", add a"Dynamic Menu Contribution"entry that points to a class with a method annotated with "@AboutToShow" that will dynamically build the menu entries and define an hanlder for each item

    public class XXX {
       @Inject private EModelService modelService;
       @AboutToShow 
       public void aboutToShow(List<MMenuElement> items, ...) {
    
          // insert your logic here to add an entry or not...
          // maybe with a loop of some sort...
          MDirectMenuItem dynamicItem = modelService.createModelElement(MDirectMenuItem.class);
          dynamicItem.setLabel(<;abel>);
          dynamicItem.setIconURI(<icon>);
          dynamicItem.setContributorURI("platform:/plugin/<your plugin name>");
          dynamicItem.setContributionURI("bundleclass://<your plugin name>/<class handler>");
          dynamicItem.getTransientData().put(<name>, <value>); // To pass parameters to the handler
    
          items.add(dynamicItem);
      }
    

    }

    public class <class handler> {
       @Execute
       public void execute(MMenuItem menuItem, ...) {
          String param = (<Type>) menuItem.getTransientData().get(<name>); // Get parameter back
          // Put your logic here linked to the menu entry
       }
    }
    

    Add an"Imperative Expression"child, link it to a class with a method annotated with "@Evaluate" expression to decide to show/hide the dynamic menu, for example if the menu is empty...

    @Evaluate
    public boolean showXXX(...) {
       return true/false; -> display/hide the whole menu
    }