Wednesday, March 23, 2011

Commands in Eclipse 4: Understanding who does what

Complementary to Commands in Eclipse 3.x: the 10 most common pattern.

A description of the Command Framework in Eclipse 4.x. Much of it remains the same; the command is still an abstraction for a semantic operation, still declared as an extension as are the handlers and menus that reference it. Expressions are still used for visibleWhen, activeWhen and enabledWhen statements.

The big difference is in the handler implementation and its supporting API:
  • An @Execute annotation is used on the method to be invoked.
  • Optionally, an @CanExecute annotation can be used on a method called by the framework to determine enablement.
  • Most objects needed by the handler are to be injected using:
    • @Inject (for service by interface)
    • @Named (for variables, e.g. selection)
    • @Preference (for the handler's plugin's preference store)
  • An IEclipseContext is used extensively.
I missed how the IEclipseContext is to be obtained but it is core to the Eclipse 4.x Workbench model and most Eclipse 4.x development, not just the handlers. It's hierarchical and can be traversed. The handler executes in the last active context, usually a ViewPart. In the model it is a leaf under a Perspective which is under a Window which is under the Application root. The effect of this hierarchy is that a command's state, which was global in 3.x, is contextual in 4.x and can be one of many. In 3.x a command was either enabled or disabled and if there were two menu items in two separate views for a single command, e.g. print, they were both either enabled or disabled... which often made no sense. In 4.x they are separate contexts and so individual states.

It's comforting that plugin.xml extensions can probably be left as they are and that only the handlers need migration. Though the injection and context use is radically different, it is also apparent it is leaner code and that, once learned, is portable to the rest of RCP development.

No comments:

Post a Comment