Tuesday, December 16, 2008

Sunday, December 07, 2008

Hooking into Eclipse command execution

When I was working on implementing the Clips plug-in I wanted to intercept the Cut and Copy actions and automatically create clips from the selection. To my delight I discovered the necessary mechanism to exactly do that. Basically I had to add the following listener:
// Add listener to monitor Cut and Copy commands
ICommandService commandService = (ICommandService) PlatformUI
.getWorkbench().getAdapter(ICommandService.class);
if (commandService != null) {
commandService.addExecutionListener(new IExecutionListener() {

public void notHandled(String commandId,
NotHandledException exception) {
}

public void postExecuteFailure(String commandId,
ExecutionException exception) {
}

public void postExecuteSuccess(String commandId,
Object returnValue) {
// Is it a Cut or Copy command
if ("org.eclipse.ui.edit.copy".equals(commandId)
|| "org.eclipse.ui.edit.cut".equals(commandId)) {
Clipboard clipboard = new Clipboard(PlatformUI
.getWorkbench().getActiveWorkbenchWindow()
.getShell().getDisplay());
Object contents = clipboard
.getContents(TextTransfer.getInstance());
if (contents instanceof String) {
// Now do something with text selection
}
}

}

public void preExecute(String commandId, ExecutionEvent event) {
}

});
}

Cool huh?