Tuesday, January 20, 2009

Eclipse RCP: Command, Handler enabledWhen with a particular selection object

Command Framework
Command framework allows to add menubar and toolbar actions via handlers. To create a command in the application.

Create an extension of the commands


<extension point="org.eclipse.ui.commands">
<command defaulthandler="com.mycomp.app1.commands.SampleHandler" id="com.mycomp.app1.commands..SampleCommand" name="Add User">
</command>
</extension>

Implement the SampleHandler which is the default handler for the command. The handler should implement the interface IHandler or can simply extend AbstractHandler. Now we can add the Command to application main menubar, toolbar or to a menubar and toolbar of a view.

To add it a to a view's toolbar


<extension point="org.eclipse.ui.menus">
<menucontribution locationuri="toolbar:com.mycomp.app1.SampleView">
<command commandid="com.mycomp.app1.commands.SampleCommand" icon="icons/sample.png" label="Sample" style="">
</command>
</menucontribution>
</extension>

This will add the handler to the SampleView's toolbar. But to activate this, we need to have activeWhen command expression.


<activeWhen>
<equals variable="activePartId">
<value="com.mycomp.app1.SampleView"/>
</with>
</activeWhen>


Now the SampleHandler will be on the toolbar of the view. The handler execute method can get the activepart,selection, and different workbench values from HandlerUtil class.

HandlerUtil.getActiveWorkbenchWindow(event) or HandlerUtil.getCurrentSelection(event).

To enable and disable the action based on selection, enabledWhen needs to be extended, Now lets enable the action only for one selection.


<enabledWhen>
<with variable="selection">
<value="1">
</count>
</with>
</enabledWhen>

No comments: