Skip to content

HOWTO: Use IContextActivation to setup keybindings for a ViewPart or EditorPart

April 26, 2010

Just a quick tip for setting up view-specific and editor-specific keybindings. I had a bit trouble figuring it out and it took a whole day of googling to figure it out. If you want to get view-specific or editor-specific keybindings working you should:

  1. Use the org.eclipse.ui.contexts extension point to define a new context. The context ID should be the same as your editor or viewpart ID though it doesn’t have to be. The parent ID can be most anything but org.eclipse.ui.context.window is a safe value.
  2. Use the org.eclipse.ui.bindings to define a new keybinding that is only active in your view or editor. The contextId must be the same ID you defined in the first step. A good default for schemeId is org.eclipse.ui.defaultAcceleratorConfiguration. For more about the difference between contexts and schemes see FAQ How do I provide a keyboard shortcut for my action?. It’s a little confusing but, in simplest terms, a context defines when your keybinding is active and a scheme defines what the actual accelerator shortcut for the command will be used. You provide a default but the user can re-assign the accelerator shortcut if he changes schemes.
  3. Finally you must programatically activate the context when your view or editor is opened. How you do this is important. (This is the tricky part.) If you want the keybindings to be only active when your view is in focus you should use the “site-specific service locator” ie IContextService contextService = (IContextService) getSite().getService(IContextService.class);. If you want your keybindings to always be active you should use the “workbench service locator” ie IContextService contextService = (IContextService) PlatformUI.getWorkbench().getService(IContextService.class);. If you use the site-specific service locator the deactivation of your context will all be automagically handled for you.

Enjoy.

Advertisements

From → eclipse

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: