Making a Selection Programmatically (Modifying Eclipse ExecutionEvent Context)

by rgrunber

Have you ever wanted to reuse a command / action but needed to modify certain things (eg. the elements selected) just before the command was activated ? For example, you have an action that can only be performed when a selection is made. One would think to make the selection programmatically, but is it really necessary to go through the UI just to provide some information ? I managed to find a post describing how to go about this, but it’s worth repeating.

All this information is passed when the command is run as an ExecutionEvent . This has a method Object getApplicationContext() which will return an Object that may be cast to an IEvaluationContext . This, in turn has a method void addVariable(String, Object) that can be used to modify the context.

In my case, setting the context to indicate 2 items had been selected was simply a matter of adding the following code :

IEvaluationContext ctx = (IEvaluationContext) event.getApplicationContext()
ctx.addVariable(ISources.ACTIVE_SELECTION_NAME,
  new StructuredSelection(new IResource [] {oldFile, newFile}))

Now you can call your action / command and make sure to pass the ExecutionEvent.

ICommandService cmdService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
Command cmd = cmdService.getCommand("my.command.id");
try {
  cmd.executeWithChecks(event);
} catch (Exception e) {
  // Error handling
}
Advertisements