Skip to main content
Jump to: navigation, search

Platform Command Framework

Revision as of 14:38, 30 October 2006 by (Talk | contribs) (Generic Command Action Delegate)

Architecture Overview

Figure 1: High Level Architecture


Commands are managed by the org.eclipse.ui.commands extension point and the ICommandService.

An example of using the extension point to create a command:

         description="Actions take at lunch time."
         description="Go for the taco."
         name="Eat That Taco">

You can programmatically create commands as well. From within a view:

ICommandService cmdService = (ICommandService) getSite().getService(
Category lunch = cmdService
if (!lunch.isDefined()) {
  lunch.define("Lunch", "Actions take at lunch time.");
Command eatTaco = cmdService
if (!eatTaco.isDefined()) {
  eatTaco.define("Eat That Taco", "Go for the taco.", lunch);

Note, however, that a plugin that programmatically defines commands is responsible for cleaning them up if the plugin is ever unloaded.

Also, like IAction you can execute a command directly ... but to get the proper environment it's better to execute it through the IHandlerService. See #Handlers.

In 3.1, it's not possible to execute through the handler service, but you can provide almost the same execution environment.

Command eatTaco = cmdService
eatTaco.execute(new ExecutionEvent(Collections.EMPTY_MAP, null, handlerService.getCurrentState()));

Executing a command with parameters

When a Command specifies its parameters, it can also specify a parameter type and/or some valid values. For example, the showView command.

       values="org.eclipse.ui.internal.registry.ViewParameterValues" />

To execute this command, you need to create a ParameterizedCommand with a Parameterization (an instance of a parameter and its value).

		ICommandService commandService = ...;
		IHandlerService handlerService = ...;
		Command showView = commandService
		IParameter viewIdParm = showView

		// the viewId parameter provides a list of valid values ... if you
		// knew the id of the problem view, you could skip this step.
		// This method is supposed to be used in places like the keys
		// preference page, to allow the user to select values
		IParameterValues parmValues = viewIdParm.getValues();
		String viewId = null;
		Iterator i = parmValues.getParameterValues().values().iterator();
		while (i.hasNext()) {
			String id = (String);
			if (id.indexOf("ProblemView") != -1) {
				viewId = id;

		Parameterization parm = new Parameterization(viewIdParm, viewId);
		ParameterizedCommand parmCommand = new ParameterizedCommand(
				showView, new Parameterization[] { parm });

		handlerService.executeCommand(parmCommand, null);

This executes the showView command with the problem view id. This is done for us when declaratively specifying a keybinding.

     sequence="M2+M3+Q X"
       value="org.eclipse.ui.views.ProblemView" />

Using an IActionDelegate to execute a command

This is still under construction, but basically you can write a generic IActionDelegate that will execute commands for you.

For example, in the above section we saw the showView command takes one parameter, the view id. What if you wanted to call the command from an actionSet?

You can specify the action using the <class/> element instead of the class attribute ... you'll get a couple of warnings, ignore them.

              label="Show View:Outline"
           <class class="org.eclipse.ui.examples.actions.actions.GenericCommandActionDelegate">
              <parameter name="commandId" 
              <parameter name="org.eclipse.ui.views.showView.viewId" 
              label="Show View:Bookmark"
           <class class="org.eclipse.ui.examples.actions.actions.GenericCommandActionDelegate">
              <parameter name="commandId" 
              <parameter name="org.eclipse.ui.views.showView.viewId" 

For commands without parameters, you can use the class attribute short from:


Now your action definition looks more like a keybinding definition. You are specifying the command id and any parameters needed for that action.

Known Issues:

When you start up eclipse you'll get warnings about your actions not having a class attribute. It's not an error, and won't effect the action performance.

You'll also see the actions in the Uncategorized section of the keybindings page. You can bind keys to them but they won't work from the keybinding. That's OK, you should be binding keys to the command not the action.

Generic Command Action Delegate

We'll need a more robust implementation, but in 3.2 your action delegate needs to look something like the class below. I've only tested this with org.eclipse.ui.actionSets, but it should work with the viewActions, editorActions, and popupMenus extension points as well.

 * Copyright (c) 2005, 2006 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * Contributors:
 *     IBM Corporation - initial API and implementation
package org.eclipse.ui.examples.actions.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.IParameter;
import org.eclipse.core.commands.Parameterization;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.handlers.IHandlerService;

 * This action delegate can be used to specify a command with or without
 * parameters be called from an <action/> specified in actionSets,
 * editorActions, viewActions, or popupMenus.
public class GenericCommandActionDelegate implements
        IWorkbenchWindowActionDelegate, IViewActionDelegate,
        IEditorActionDelegate, IObjectActionDelegate, IExecutableExtension {

    private static final String PARM_COMMAND_ID = "commandId";

    private String commandId = null;

    private Map parameterMap = null;

    private ParameterizedCommand parameterizedCommand = null;

    private IHandlerService handlerService = null;

     * (non-Javadoc)
     * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
    public void dispose() {
        handlerService = null;
        parameterizedCommand = null;
        parameterMap = null;

     * (non-Javadoc)
     * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
    public void run(IAction action) {
        if (handlerService == null) {
            // what, no handler service ... no problem
        try {
            if (commandId != null) {
                handlerService.executeCommand(commandId, null);
            } else if (parameterizedCommand != null) {
                handlerService.executeCommand(parameterizedCommand, null);
            // else there is no command for this delegate
        } catch (Exception e) {
            // exceptions reduced for brevity
            // and we won't just do a print out :-)

     * (non-Javadoc)
     * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
     *      org.eclipse.jface.viewers.ISelection)
    public void selectionChanged(IAction action, ISelection selection) {
        // we don't care, handlers get their selection from the
        // ExecutionEvent application context

     * (non-Javadoc)
     * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement,
     *      java.lang.String, java.lang.Object)
    public void setInitializationData(IConfigurationElement config,
            String propertyName, Object data) throws CoreException {
        // save the data until our init(*) call, where we can get
        // the services.
        if (data instanceof String) {
            commandId = (String) data;
        } else if (data instanceof Map) {
            parameterMap = (Map) data;

     * Build a command from the executable extension information.
     * @param commandService
     *            to get the Command object
    private void createCommand(ICommandService commandService) {
        String id = (String) parameterMap.get(PARM_COMMAND_ID);
        if (id == null) {
        if (parameterMap.size() == 1) {
            commandId = id;
        try {
            Command cmd = commandService.getCommand(id);
            if (!cmd.isDefined()) {
                // command not defined? no problem ...
            ArrayList parameters = new ArrayList();
            Iterator i = parameterMap.keySet().iterator();
            while (i.hasNext()) {
                String parmName = (String);
                if (PARM_COMMAND_ID.equals(parmName)) {
                IParameter parm = cmd.getParameter(parmName);
                if (parm == null) {
                    // asking for a bogus parameter? No problem
                parameters.add(new Parameterization(parm, (String) parameterMap
            parameterizedCommand = new ParameterizedCommand(cmd,
                    (Parameterization[]) parameters
                            .toArray(new Parameterization[parameters.size()]));
        } catch (NotDefinedException e) {
            // command is bogus? No problem, we'll do nothing.

     * (non-Javadoc)
     * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
    public void init(IWorkbenchWindow window) {
        if (handlerService != null) {
            // already initialized

        handlerService = (IHandlerService) window
        if (parameterMap != null) {
            ICommandService commandService = (ICommandService) window

     * (non-Javadoc)
     * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
    public void init(IViewPart view) {

     * (non-Javadoc)
     * @see org.eclipse.ui.IEditorActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction,
     *      org.eclipse.ui.IEditorPart)
    public void setActiveEditor(IAction action, IEditorPart targetEditor) {
        // we don't actually care about the active editor, since that
        // information is in the ExecutionEvent application context
        // but we need to make sure we're initialized.
        if (targetEditor != null) {

     * (non-Javadoc)
     * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction,
     *      org.eclipse.ui.IWorkbenchPart)
    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
        // we don't actually care about the active part, since that
        // information is in the ExecutionEvent application context
        // but we need to make sure we're initialized.
        if (targetPart != null) {


Handlers are managed by the org.eclipse.ui.handlers extension point and the IHandlerService. Many Handlers can register for a command. At any give time, either 0 or 1 handlers will be active for the command. A handler's active state and enabled state can be controlled declaratively.

         <with variable="activeContexts">
            <iterate operator="or">
               <equals value="z.ex.view.keybindings.contexts.taco"/>

Here the handler is checking the activeContexts variable (See org.eclipse.ui.ISources) and if the "taco" context is active, the handler is active.

The handler itself, TacoHandler, must implement IHandler but would usually be derived from the abstract base class org.eclipse.core.commands.AbstractHandler.

You can create and activate a handler programmatically:

IHandlerService handlerService = (IHandlerService) getSite()
IHandler handler = new AbstractHandler() {
  public Object execute(ExecutionEvent event)
          throws ExecutionException {
    System.out.println("Eat that Taco");
    return null;
    .activateHandler("z.ex.view.keybindings.eatTaco", handler);

Apparently, to run commands we should be calling the IHandlerService, not the Command object execute method itself.

handlerService.executeCommand("z.ex.view.keybindings.eatTaco", null);


KeyBindings are managed by the org.eclipse.ui.bindings extension point and the IBindingService. Keybindings cannot be updated programmatically.


A key binding is active when the context is active.


Contexts are managed by the org.eclipse.ui.contexts extension point and the IContextService.

Most contexts are created by the extension point, and activated programmatically when appropriate. But you can create contexts programmatically as well. The active contexts usually form a tree, although in the case of keybindings this tree is narrowed down to a branch.

         description="To allow the consumption of Tacos"
         name="Mexican Food"

For a context that was attached to a view, it would normally be activated in the view's createPartControl(*) method.

IContextService contextService = (IContextService) getSite()
IContextActivation contextActivation = contextService.activateContext("z.ex.view.keybindings.contexts.taco");

You can only de-activate a context that you are responsible for activating.

Programmatically, you can create contexts:

Context tacos = contextService
if (!tacos.isDefined()) {
  tacos.define("Mexican Food", "To allow the consumption of Tacos",

Note, however, that a plugin that programmatically defines contexts is responsible for cleaning them up if the plugin is ever unloaded.

Tracing Option

There are a couple of reasons why keybindings and commands might not work.

  1. Keybindings are in a context that is not active
  2. There is a keybinding conflict
  3. No handler is currently active for the command
  4. There is a handler conflict

To help track down the problem, you can run with debug tracing options. For example:


I put these options in a debug.options file and run eclipse using:

bash$ eclipse -debug debug.options -data /opt/local/pw_workspace >debug.log 2>&1

This logs the debug output to the debug.log file. This works on windows as well:

C:\development> eclipse32\eclipse.exe -debug debug.options -data workspaces\pw_workspace >debug.log 2>&1

handlers.verbose.commandId allows you to track the information about a specific command that isn't working. is the open type dialog (normally CTRL+SHIFT+T) and org.eclipse.ui.edit.copy (commented out) is COPY (normally CTRL+C)

Back to the top