Search code examples
javaswteclipse-rcp

Getting the Visibility of a Handler


Out base plug-ins define commands and handler, which the application later enables or disables or makes (in)visible. Now I'm trying to evaluate a double click and need to access a command. That's easy:

private boolean executeCommand(String commandId) {
    IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class);
    try {
        handlerService.executeCommand(commandId, null);
        return true;
    } catch (ExecutionException | NotDefinedException | NotEnabledException
            | NotHandledException e) {
        MessageUtil.logError(e);
        return false;
    }
}

Now the problem is: There are two handlers ("edit" and "view") which are possible to be executed, and I want to only execute "edit" when it's there, else "view".

    ICommandService commandService = (ICommandService) getSite().getService(ICommandService.class);
    Command command = commandService.getCommand(commandId);
    IHandler handler = command.getHandler();

I tried asking the command for isDefined(), isEnabled() and isHandled() and the handler for isEnabled() and isHandled(), but everything returns true.

How do I find out if the handler is visible?


Solution

  • I think I finally found the answer:

    public boolean isCommandEnabled(String commandId) {
        final IWorkbenchActivitySupport activitySupport = PlatformUI.getWorkbench().getActivitySupport();
        final IActivityManager activityManager = activitySupport.getActivityManager();
    
        for (String activityId : (Set<String>) activitySupport.getActivityManager().getDefinedActivityIds()) {
            // we iterate through all activities...
            IActivity activity = activityManager.getActivity(activityId);
            for (IActivityPatternBinding activityBinding : (Set<IActivityPatternBinding>) activity.getActivityPatternBindings()) {
                // ...and check if one of the bindings match the command...
                if (isMatch(activityBinding, commandId) && !activity.isEnabled()) {
                    // ... to get the command's enablement
                    return false;
                }
            }
        }
        // if no activity was found to disable the command, it's enabled by default
        return true;
    }
    
    private static boolean isMatch(IActivityPatternBinding activityBinding, String toMatch) {
        return activityBinding.getPattern().matcher(toMatch).matches();
    }
    

    I don't really know if this is normal or just for our applications, but the commandId in this is case is something along the lines of org.acme.plugin/org.acme.plugin.commands.commandId.