snim2
snim2

Reputation: 4079

Implementing handlers in an Eclipse Plugin

I have a handler in an Eclipse plugin (developed on Indigo) that I want to run every time a Java file in a text editor is saved (or opened, ideally). As far as I can gather, there are two ways of achieving this:

  1. Programattically via the CommandService API.
  2. Using the configuration in plugin.xml

I've tried both of these. Method 1 like this:

public class Activator extends AbstractUIPlugin {
    @Override
    public void start(final BundleContext context) throws Exception {
        super.start(context);
        ICommandService commandService = (ICommandService) PlatformUI
              .getWorkbench().getService(ICommandService.class);
        commandService.addExecutionListener(new MyListener());
        plugin = this;
    }
    ...
}

public class MyListener implements IExecutionListener {
    @Override
    public void postExecuteSuccess(final String commandId, final Object returnValue) {
        System.out.println("PostEventSuccess:" + commandId);
    }

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

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

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

and method 2. like this:

<extension point="org.eclipse.ui.handlers">
    <handler 
        commandId="org.eclipse.ui.file.save"
        class="mypackage.MyHandler">
        <activeWhen>
            <with variable="activeWorkbenchWindow">
                <instanceof value="org.eclipse.ui.IWorkbenchWindow"/>
            </with>
        </activeWhen>
    </handler>
</extension> 

Method 1. doesn't run my listener at all. Method 2. works, in that the handler is executed, but my handler seems to replace the default handler. When the user tries to save the file my handler runs but the file doesn't get saved. The handler itself seems to be fine (I've tested it by creating a menu item that runs it).

Is Method 1. deprecated now or have I implemented the service incorrectly? How do I get method 2. to save a file? Can the default handler be run from my handler?

Upvotes: 1

Views: 2675

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200158

These two do not differ just in that one is programmatic and the other declarative. I think defining the command handler is wrong as this handles the command execution instead of just being notified that the command was executed. Your first approach seems fine, but your code doesn't get executed until the plugin has been activated, which happens lazily, when the first class from your bundle is loaded. There is a workaround in Eclipse: contribute to the org.eclipse.ui.startup extension point. Make e.g. your Activator class implement IStartup, you can use an empty implementation -- the only point is to get the framework to load any class from your bundle.

Upvotes: 2

Related Questions