2010-02-14

Using Adapters in Handlers to control functionality

In my last blog post about the use of Dependency injection in e4, I used adapters in handlers with functional interfaces to control the enablement of functionality in an application. By request, here is an extended version of that with some additional explanations. [Incidentally, this was proposed as a talk for EclipseCon ´10, but unfortunately got rejected...]

Note that this is only for users in larger applications - if you have a command with a single handler and simple expressions, then this is not needed at all...

Why?

When you implement a larger Eclipse RCP based application, you can run into a number of problems with handlers and menus as you add more and more objects to the domain model of your application model and more and more commands for the objects in the UI.

In order to control the visibility of menu items in menus - most notable the popup menu - you have the visibleWhen construct for the commands in the menu. The used expression often is an or-ed together version of all the activeWhen expressions for the handlers for the command in question. E.g. if you have a command C with two handlers h1 and h2, each with the activeWhen expression aw1 and aw2, then you often want the command to use the visibleWhen expression (or aw1 aw2).

But... as new objects can be added by new plug-ins and the number of commands are enlarged for the existing objects over time, how do you maintain the visibleWhen expression?

Also, very often, you have a lot of common implementation for a specific command in the different handlers for the command - this is not so surprising as the command is an abstract description of some functionality - e.g. "cut", "print", "connect", etc - and some common code must be expected no matter which object that is operated on. E.g. consider the "print" command: a lot of the code for selection of printer and print options will be common no matter which object is printed.

Finally, very often, you really don't want to introduce all the different UI functionality in the domain model itself - maybe for principle reasons or maybe because you don't "own" the code of the model and cannot modify it. You might therefore want to use adapters to handle the functionality in the cases where you cannot change model and direct methods where you can change the model.

For these different reasons I often use a common design pattern in my applications that incorporate functional interfaces for the different commands, adapters for the implementations and some very simple handlers on top - and not least some very easy-to-maintain menu and handler expressions.

In the following, I have used a very simple RCP application as the example with just a single view that shows a table with a number of objects. The objects are Contacts - with name and address -, Customers - extends Contact with a segment - and Segment - with just a segment. [Yes, we could have used a set of model interfaces in this example as well, as we would if we had just used EMF for the model, but in many domain models, that is just not possible...] The table have a popup menu with just a single command "Show Segment" that should be shown for all Customers and Segments, but not for the Contacts. The command must show the segment of the selected object if relevant.

The complete test application can be found here.

How...

First, I use a functional interface for each of the domain model commands in the application. These interfaces have a number of methods used by the command handler to execute the wanted operation. Often this is just a single method, but there can be multiple methods for more complex scenarios.

In this case, the functional interface could be as follows:

public interface IDoShowSegment {
  void doShowSegment(Shell shell);
}

The doShowSegment method could also have been getSegmentName...

In my example, the Customer class implements the interface directly, whereas the Segment class does not, but have an adapter factory instead. The relevant part of the Command class looks as follows:

public class Customer extends Contact implements IDoShowSegment {
  // ...

  @Override
  public void doShowSegment(Shell shell) {
    MessageDialog.openInformation(shell, "The customer segment is...", getSegment());
  }
}

And the relevant part of the adapter factory looks as follows:

public class SegmentAdapterFactory implements IAdapterFactory {
  @Override
  public Object getAdapter(Object adaptableObject, Class adapterType) {
    if (!(adaptableObject instanceof Segment)) {
      return null;
    }
    final Segment s = (Segment) adaptableObject;
    if (adapterType == IDoShowSegment.class) {
      return new IDoShowSegment() {
        @Override
        public void doShowSegment(Shell shell) {
          MessageDialog.openInformation(shell, "The segment is...", s.getSegment());
        }
      };
    }
    return null;
  }

  // ...
}

The factory is installed using the adapters extension point

<extension point="org.eclipse.core.runtime.adapters">
  <factory
      adaptableType="com.rcpcompany.ex.adapterhandlers.model.Segment"
      class="com.rcpcompany.ex.adapterhandlers.adapters.SegmentAdapterFactory">
    <adapter type="com.rcpcompany.ex.adapterhandlers.functionality.IDoShowSegment" />
  </factory>
</extension>

[The used functional interface isn't perfect, as it forces the adapter factory to construct a new object for each call to the getAdapter method. It can be helped by changing the method to doShowSegment(Object,Segment), but... for the sake of simplicity...]

To invoke the "Show Segment" functionality for a specify object, we when have to do the following:

final IDoShowSegment showSegment = (IDoShowSegment)Platform.getAdapterManager().getAdapter(element, IDoShowSegment.class);
if (showSegment != null) {
  final Shell shell = ...;
  showSegment.doShowSegment(shell);
}

Note that we here just ignore the case where the object cannot be adapted to our functional interface.... Also note that the getAdapter method of the adapter manager automatically checks if 1) the object directly implements the interface, 2) the object implements the IAdaptable interface - and then uses this, or 3) if an adapter factory is installed for the interface and object class.

In the context of the handler, this is as follows - with the obvious declarations for the handler.

public class ShowSegmentHandler extends AbstractHandler implements IHandler {
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    final ISelection selection = HandlerUtil.getCurrentSelectionChecked(event);
    if (!(selection instanceof IStructuredSelection)) {
      return null;
    }
    final IStructuredSelection ss = (IStructuredSelection) selection;
    final Object element = ss.getFirstElement();
    final IDoShowSegment showSegment = (IDoShowSegment) Platform.getAdapterManager().getAdapter(element,
        IDoShowSegment.class);
    if (showSegment == null) {
      return null;
    }
    final Shell shell = HandlerUtil.getActiveShellChecked(event);
    showSegment.doShowSegment(shell);
    return null;
  }
}

With the above code and a menus extension, the "Show Segment" command is shown as enabled in the popup menu for all items - even the Contact objects.

To make the handler only active when the selection is an object that supports the functional interface, use the following handlers declaration:

<extension point="org.eclipse.ui.handlers">
  <handler
        class="com.rcpcompany.ex.adapterhandlers.handlers.ShowSegmentHandler"
        commandId="com.rcpcompany.ex.adapterhandlers.commands.ShowSegment">
    <activeWhen>
      <iterate ifEmpty="false" operator="and">
        <adapt type="com.rcpcompany.ex.adapterhandlers.functionality.IDoShowSegment" />
      </iterate>
    </activeWhen>
  </handler>
</extension>

With this declaration the command is only enabled in the popup menu when relevant, though it is still shown for the Contact objects.

To show the command only when an active handler exists, use the following visibleWhen expression:

<extension point="org.eclipse.ui.menus">
  <menuContribution locationURI="popup:org.eclipse.ui.popup.any">
    <command commandId="com.rcpcompany.ex.adapterhandlers.commands.ShowSegment" style="push">
      <visibleWhen checkEnabled="false">
        <iterate ifEmpty="false" operator="and">
          <adapt type="com.rcpcompany.ex.adapterhandlers.functionality.IDoShowSegment" />
        </iterate>
      </visibleWhen>
    </command>
  </menuContribution>
</extension>

Note that this only use the activeWhen expression to control the visibility of the command in the menu. This is slightly different from the visibleWhen with checkEnabled=true, which is based on the enabledWhen expression.

The End Result

The end result is that if you want to implement the command for a new or existing object you must either extend the object with the functional interface or add an adapter for the object class to the functional interface - I usually prefer the later.

To find the objects that supports the command, just look for implementations of the interface - which by the way I normally name "IDo<command-id>" - here IDoShowSegment.

Useful? In larger applications, yes - in small applications, this is probably like shooting flies with canons. Is it worth the added code and the redirection in the handler? That can only be decided by you...

2010-02-12

Dependency Injection in e4 - just why do we want to do that?

Lately, I have been giving a number of presentations of Eclipse e4. The focus has been on the changes that we will see when we program for e4 rather than 3.x.

With all the presentations, there have been a very lively discussion on the pros and cons of the new technologies in e4, but one subject in particular have been discussed: the use of Dependency Injection (DI) and what it will mean for productivity, testing and the tooling in Eclipse we all have grown so used to.

The following examples are taken from the excellent e4 contact manager by Kai Tödter that shows off some of the interesting features of e4 including theming and DI. The manager is very e4'ish and use the e4 features as these are probably meant to be used - with other words, I don't fault Kai for the examples or the problems I find in the examples.

At first glance the use of DI seems to give some very understandable code and it has the potential to do away with some of the listener code that we see in many places in 3.x code.

E.g. to follow the current selection in a view - here just expecting a single selected object - you would do something like the following in 3.x (forget about removing the listener again...):

public class DetailsView extends ViewPart {
  @Override
  public void createPartControl(Composite parent) {
    // ...

    final ISelectionService ss = getSite().getWorkbenchWindow().getSelectionService();
    ss.addPostSelectionListener(myListener);
    myListener.selectionChanged(null, ss.getSelection());
  }

  protected void setSelection(Contact contact) {
    // ... do something with the selection
  }

  private final ISelectionListener myListener = new ISelectionListener() {
    @Override
    public void selectionChanged(IWorkbenchPart part, ISelection selection) {
      if (!(selection instanceof IStructuredSelection)) {
        setSelection(null);
        return;
      }

      final IStructuredSelection ss = (IStructuredSelection) selection;
      if (ss.isEmpty() || !(ss.getFirstElement() instanceof Contact)) {
        setSelection(null);
        return;
      }
      setSelection((Contact) ss.getFirstElement());
    }
  };

  // ...
}

whereas, you will just do something like this in e4:

public class DetailsView {
  @Inject
  public void setSelection(@Optional @Named(IServiceConstants.SELECTION) Contact contact) {
    // ... do something with the selection
    
  }

  // ...
}

So far, so good. A lot less code compared with the 3.x version and the intension is quite clear once you know the injection is persistent, so changes in the context is automatically propagated to the view.

The main difference between the two versions lies in the way that you find and access services: in 3.x you basically have a Java method chain - here getSite().getWorkbenchWindow().getSelectionService() - where the e4 version uses a magic class or string - here @Optional @Named(IServiceConstants.SELECTION). The general Java tooling helps us access the services in 3.x, but what type of tooling will help us in e4? And how will we get warned about accidental changed in the e4 string?

A much more problematic example - as far as I am concerned - can be found in the SaveHandler of the contact manager. This handler is used to save the current contact in the details view by delegating the save functionality to the doSave method of the view (Again, I have cut away some irrelevant stuff):

public class SaveHandler {
  public void execute(IEclipseContext context, @Optional IStylingEngine engine,
      @Named(IServiceConstants.ACTIVE_SHELL) Shell shell,
      @Named(IServiceConstants.ACTIVE_PART) final MContribution contribution) throws InvocationTargetException,
      InterruptedException {
    final IEclipseContext pmContext = EclipseContextFactory.create(context, null);

    final ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
    dialog.open();

    dialog.run(true, true, new IRunnableWithProgress() {
      public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
        pmContext.set(IProgressMonitor.class.getName(), monitor);
        Object clientObject = contribution.getObject();
        ContextInjectionFactory.invoke(clientObject, "doSave", pmContext, null);
      }
    });
    // ...
  }
}

Basically the handler creates a new context for the operation, opens a progress dialog, installs the progress monitor in the context, and then delegates to the doSave method with the new context.

The problem is found in the inner run methods: the name of the method of the view that is used to do the save operation itself is hard-coded as a string. How is this ever going to work with the Java tooling? How can we get quick assists or refactoring to work here? And how will we maintain this?

There are also some other problems with regards to testability. E.g. if a new doSave is ever created in the view, this will not provoke either a compile-time or a run-time error, but instead just execute both methods.

In the 3.x version, I would let the views that supports the doSave method implement a common Java interface - e.g. IDoSaveable and then test for this in the handler. An example of how this can be done is shown below:

The interface:

public interface IDoSaveable {
  void doSave(IProgressMonitor monitor);
}

The view:

public class DetailsView extends ViewPart implements IDoSaveable {
  @Override
  public void createPartControl(Composite parent) {
    // ...
  }

  @Override
  public void doSave(IProgressMonitor monitor) {
    // ... do save
  }
}

The handler - note that this version uses adaption, but you could use instanceof instead:

public class SaveHandler extends AbstractHandler {
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    final IWorkbenchPart part = HandlerUtil.getActivePartChecked(event);
    final IDoSaveable saveablePart = (IDoSaveable) Platform.getAdapterManager().getAdapter(part, IDoSaveable.class);
    if (saveablePart != null) {
      final Shell shell = HandlerUtil.getActiveShellChecked(event);
      final ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
      dialog.open();

      dialog.run(true, true, new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
          saveablePart.doSave(monitor);
        }
      });
    }
    return null;
  }
}

Personally I see many advantages with this version:
  • It is actually more readable, as it has very little magic - aprt from the use of the adaption
  • It is easy to find all the views that supports the save operation.
  • Everything is based on the Java tooling and we have a no magic constants of any sorts
  • Refactoring works!
  • The activeWhen expression for the handler can simply test whether the activePart adapts to IDoSaveaeble.
What do you think? Is the new magic DI code worth the lost functionality in the Java tooling? Can we invent some new tooling to make up for the lost functionality? 

    Javagruppen - the Java user group in Denmark - yearly conference

    Javagruppen - the Java user group in Denmark - have had very interesting two-day conference at Hindsgavl Slot on Fyn.

    On the first day, I first talked about Eclipse e4 and what you should expect compared with the current 3.x versions. The presentation was well received and there was a very lively discussion about the pros and cons of the different changes that are made in e4. I almost didn't have the time for the look at the code... You can find the slides here.

    I then heard Heiko Seeberger talk about Scale and Lift. Scala is cool - very cool - for an old Lisp developer like me. If only I could find the time to integrate this with PDE, then it would be extremely cool. Heiko? Lift? I don't know... I'm not into web design so to me there are just too much magic involved in this...

    Then Agata Przybyszewska talked about RSpec and Cucumber for UI and functional testing. I'm not sure I understood all, but then I have never been looking into Ruby or RSpec.

    Next day, Jeppe Cramon first talked about how they have generated code from models in a number of projects using TigetMDSD. Very smart and definitely something that scales way better than JET from EMF.

    Last I heard Tommy Dejbjerg Pedersen talk about Google Android & Wave. Rather interesting - now I see a reason to get involved in Wave. And Tommy gave me not reasons to regret my

    I look forward to next year. If just it wasn't cold outside...