I have a command that I have added to the context menu of a view (which has a treeviewer) and the context menu of my custom editor.
In my handler is there any way for me to differentiate which context menu the command has been called from? This is because in the case of the view, I use something like this to get the data I need,
ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
.getActivePage().getSelection();
if (selection != null & selection instanceof IStructuredSelection)
{
IStructuredSelection strucSelection = (IStructuredSelection) selection;
.....
In the case of the editor, the selection is null, of course. So I added the following to handle the editor part,
IEditorPart editor = HandlerUtil.getActiveEditor(event);
IEditorInput input = editor.getEditorInput();
IPath path = ((FileEditorInput)input).getPath();
But what happens is that even if I execute this command from my view, it always returns an active editor. Does this mean I have to write to separate handlers that will be active based on whether the view or the editor is in focus?
Thank you!
2 Answers 2
Does this mean I have to write to separate handlers that will be active based on whether the view or the editor is in focus?
Yes it does. However, your separate handlers can be small classes that call a common class to do most of the work of your command. I don't know what data your command needs to function, but your separate handlers can prepare that data and pass it to the common class through one or more constructors.
You can have the same handler, and decide on the behaviour based on HandlerUtil.getActiveEditor(event) (which is only non-null when the active part is an editor) and HandlerUtil.getActiveView(event) (which is only non-null when the active part is a view).
Or you can let your handler implement IExecutableExtension and supply the method setInitializationData(IConfigurationElement config, String propertyName, Object data)' which is invoked when the handler is created. Heredatais usually given in theclassattribute of the handler declaration (see the Javadoc ofsetInitializationData`)...
In this case, I would prefer the former method, but I often use the later method whenever I cannot decide the behaviour at runtime.
6 Comments
getActiveView(...) only returns a view when the view is in fact active...
HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection()toHandlerUtil.getCurrentSelectionChecked(event)... :-)