Search code examples
eclipsepluginseclipse-plugine4

Eclipse plugin development - ToolItem strange behavior at enabling


I defined a HandledToolItem in fragment.e4xmi :

<fragments xsi:type="fragment:StringModelFragment" xmi:id="_rva08KK6Eeealvq0OCaXXw" featurename="trimContributions" parentElementId="org.eclipse.e4.legacy.ide.application">
    <elements xsi:type="menu:TrimContribution" xmi:id="_NDOigKK8Eeealvq0OCaXXw" elementId="xyz.trimcontribution.0" parentId="org.eclipse.ui.main.toolbar" positionInParent="after=additions">
      <children xsi:type="menu:ToolBar" xmi:id="_NXC2YKK8Eeealvq0OCaXXw" elementId="xyz.toolbar.1" accessibilityPhrase="ToolItems1">
        <children xsi:type="menu:HandledToolItem" xmi:id="_dOkvwKK8Eeealvq0OCaXXw" elementId="xyz.handledtoolitem.1" label="Item1" iconURI="platform:/plugin/xyz-plugin/resources/icons/toolbar/Item1.png" tooltip="" enabled="false" command="_SALb4JItEee5yvRIuSvsRg"/>
       </children>
    </elements>
  </fragments>

I can enable/disable toolItem with setEnable method, but when I click some elsewhere on the UI toolItem state always change to enabled, regardless which state is had before.

I work in Eclipse E4.


Solution

  • The enable status of a tool or menu item is updated from the current handler's @CanExecute method regularly so you can't just call setEnabled to change its state. If there isn't a @CanExecute method, true is assumed.

    Instead implement a @CanExecute method in the handler that returns the enablement state:

    @CanExecute
    public boolean canExecute()
    {
      return // TODO enabled state
    }
    

    If you want to change the enabled state during the main @Execute method of the handler you may need to force Eclipse to call the @CanExecute method. You do this using a special topic of the event broker:

    @Execute
    public void execute(MHandledToolItem mitem, IEventBroker eventBroker)
    {
       ... other code
    
       // Update enablement
       eventBroker.send(UIEvents.REQUEST_ENABLEMENT_UPDATE_TOPIC, mitem.getElementId());
    }