Search in sources :

Example 11 with Category

use of org.eclipse.core.commands.Category in project Pydev by fabioz.

the class InteractiveConsoleCommand method syncCommands.

/**
 * Makes sure that the commands are always updated (to be called in the UI-thread). Not thread safe.
 */
private static void syncCommands() {
    IWorkbench workbench;
    try {
        workbench = PlatformUI.getWorkbench();
    } catch (Throwable e) {
        // Log.log(e); -- don't even log (if we're in a state we can't use it, there's no point in doing anything).
        return;
    }
    ICommandService commandService = workbench.getService(ICommandService.class);
    // Note: hardcoding that we want to deal with the PyDev editor category.
    Category pydevCommandsCategory = commandService.getCategory("org.python.pydev.ui.category.source");
    if (!pydevCommandsCategory.isDefined()) {
        Log.log("Expecting org.python.pydev.ui.category.source to be a a defined commands category.");
        return;
    }
    // First we have to remove bindings which would conflict.
    final Set<KeySequence> removeKeySequences = new HashSet<>();
    List<InteractiveConsoleCommand> existingCommands = InteractiveConsoleCommand.loadExistingCommands();
    for (InteractiveConsoleCommand interactiveConsoleCommand : existingCommands) {
        try {
            removeKeySequences.add(KeyBindingHelper.getKeySequence(interactiveConsoleCommand.keybinding));
        } catch (Exception e) {
            Log.log("Error resolving: " + interactiveConsoleCommand.keybinding, e);
        }
    }
    BindKeysHelper bindKeysHelper = new BindKeysHelper(PyEdit.PYDEV_EDITOR_KEYBINDINGS_CONTEXT_ID);
    bindKeysHelper.removeUserBindingsWithFilter(new IFilter() {

        @Override
        public boolean removeBinding(Binding binding) {
            TriggerSequence triggerSequence = binding.getTriggerSequence();
            if (removeKeySequences.contains(triggerSequence)) {
                return true;
            }
            ParameterizedCommand command = binding.getParameterizedCommand();
            if (command == null) {
                return false;
            }
            String id = command.getId();
            if (id.startsWith(USER_COMMAND_PREFIX)) {
                return true;
            }
            return false;
        }
    });
    Map<String, InteractiveCommandCustomHandler> commandIdToHandler = new HashMap<>();
    // Now, define the commands and the bindings for the user-commands.
    int i = 0;
    for (InteractiveConsoleCommand interactiveConsoleCommand : existingCommands) {
        try {
            String commandId = USER_COMMAND_PREFIX + i;
            Command cmd = commandService.getCommand(commandId);
            if (!cmd.isDefined()) {
                cmd.define(interactiveConsoleCommand.name, interactiveConsoleCommand.name, pydevCommandsCategory);
            }
            InteractiveCommandCustomHandler handler = createHandler(interactiveConsoleCommand);
            commandIdToHandler.put(commandId, handler);
            cmd.setHandler(handler);
            KeySequence keySequence;
            try {
                if (interactiveConsoleCommand.keybinding == null || interactiveConsoleCommand.keybinding.length() == 0) {
                    continue;
                }
                keySequence = KeyBindingHelper.getKeySequence(interactiveConsoleCommand.keybinding);
            } catch (IllegalArgumentException | ParseException e) {
                Log.log("Error resolving: " + interactiveConsoleCommand.keybinding, e);
                continue;
            }
            bindKeysHelper.addUserBindings(keySequence, new ParameterizedCommand(cmd, null));
        } catch (Exception e) {
            Log.log(e);
        }
        i++;
    }
    // Unbind any command we may have previously created.
    for (; i < 100; i++) {
        Command cmd = commandService.getCommand(USER_COMMAND_PREFIX + i);
        if (cmd.isDefined()) {
            cmd.undefine();
        }
    }
    bindKeysHelper.saveIfChanged();
    setCommandIdToHandler(commandIdToHandler);
}
Also used : TriggerSequence(org.eclipse.jface.bindings.TriggerSequence) Category(org.eclipse.core.commands.Category) HashMap(java.util.HashMap) ICommandService(org.eclipse.ui.commands.ICommandService) HashSet(java.util.HashSet) Binding(org.eclipse.jface.bindings.Binding) BindKeysHelper(org.python.pydev.shared_ui.bindings.BindKeysHelper) BadLocationException(org.eclipse.jface.text.BadLocationException) ExecutionException(org.eclipse.core.commands.ExecutionException) ParseException(org.eclipse.jface.bindings.keys.ParseException) IWorkbench(org.eclipse.ui.IWorkbench) IFilter(org.python.pydev.shared_ui.bindings.BindKeysHelper.IFilter) ParameterizedCommand(org.eclipse.core.commands.ParameterizedCommand) Command(org.eclipse.core.commands.Command) ParseException(org.eclipse.jface.bindings.keys.ParseException) KeySequence(org.eclipse.jface.bindings.keys.KeySequence) ParameterizedCommand(org.eclipse.core.commands.ParameterizedCommand)

Example 12 with Category

use of org.eclipse.core.commands.Category in project eclipse.platform.ui by eclipse-platform.

the class CommandProcessingAddon method createCommand.

private void createCommand(MCommand cmdModel) {
    IParameter[] parms = null;
    String id = cmdModel.getElementId();
    String name = localize(cmdModel.getCommandName(), cmdModel);
    String desc = localize(cmdModel.getDescription(), cmdModel);
    List<MCommandParameter> modelParms = cmdModel.getParameters();
    if (modelParms != null && !modelParms.isEmpty()) {
        ArrayList<Parameter> parmList = new ArrayList<>();
        for (MCommandParameter cmdParm : modelParms) {
            ParameterType parameterType = null;
            if (cmdParm.getTypeId() != null && cmdParm.getTypeId().length() > 0) {
                parameterType = commandManager.getParameterType(cmdParm.getTypeId());
            }
            parmList.add(new Parameter(cmdParm.getElementId(), cmdParm.getName(), null, parameterType, cmdParm.isOptional()));
        }
        parms = parmList.toArray(new Parameter[parmList.size()]);
    }
    Category cat = undefinedCategory;
    if (cmdModel.getCategory() != null) {
        cat = commandService.getCategory(cmdModel.getCategory().getElementId());
    }
    commandService.defineCommand(id, name, desc, cat, parms, // $NON-NLS-1$
    cmdModel.getPersistedState().get("HelpContextId"));
}
Also used : IParameter(org.eclipse.core.commands.IParameter) ParameterType(org.eclipse.core.commands.ParameterType) Category(org.eclipse.core.commands.Category) MCategory(org.eclipse.e4.ui.model.application.commands.MCategory) ArrayList(java.util.ArrayList) MCommandParameter(org.eclipse.e4.ui.model.application.commands.MCommandParameter) Parameter(org.eclipse.e4.ui.internal.workbench.Parameter) IParameter(org.eclipse.core.commands.IParameter) MCommandParameter(org.eclipse.e4.ui.model.application.commands.MCommandParameter)

Example 13 with Category

use of org.eclipse.core.commands.Category in project eclipse.platform.ui by eclipse-platform.

the class CommandToModelProcessor method generateCategories.

/**
 * @param commandManager
 */
private void generateCategories(MApplication application, CommandManager commandManager) {
    for (Category cat : commandManager.getDefinedCategories()) {
        if (categories.containsKey(cat.getId())) {
            continue;
        }
        try {
            MCategory catModel = modelService.createModelElement(MCategory.class);
            catModel.setElementId(cat.getId());
            catModel.setName(cat.getName());
            catModel.setDescription(cat.getDescription());
            application.getCategories().add(catModel);
            categories.put(catModel.getElementId(), catModel);
        } catch (NotDefinedException e) {
            // Since we asked for defined commands, this shouldn't be an
            // issue
            WorkbenchPlugin.log(e);
        }
    }
}
Also used : Category(org.eclipse.core.commands.Category) MCategory(org.eclipse.e4.ui.model.application.commands.MCategory) MCategory(org.eclipse.e4.ui.model.application.commands.MCategory) NotDefinedException(org.eclipse.core.commands.common.NotDefinedException)

Example 14 with Category

use of org.eclipse.core.commands.Category in project eclipse.platform.ui by eclipse-platform.

the class CommandPersistence method readCommandsFromRegistry.

/**
 * Reads all of the command definitions from the commands extension point.
 *
 * @param configurationElements     The configuration elements in the commands
 *                                  extension point; must not be
 *                                  <code>null</code>, but may be empty.
 * @param configurationElementCount The number of configuration elements that
 *                                  are really in the array.
 * @param commandManager            The command service to which the commands
 *                                  should be added; must not be
 *                                  <code>null</code>.
 */
private static void readCommandsFromRegistry(final IConfigurationElement[] configurationElements, final int configurationElementCount, final CommandManager commandManager) {
    final List<IStatus> warningsToLog = new ArrayList<>(1);
    for (int i = 0; i < configurationElementCount; i++) {
        final IConfigurationElement configurationElement = configurationElements[i];
        // Read out the command identifier.
        // $NON-NLS-1$
        final String commandId = readRequired(configurationElement, ATT_ID, warningsToLog, "Commands need an id");
        if (commandId == null) {
            continue;
        }
        // Read out the name.
        // $NON-NLS-1$
        final String name = readRequired(configurationElement, ATT_NAME, warningsToLog, "Commands need a name");
        if (name == null) {
            continue;
        }
        // Read out the description.
        final String description = readOptional(configurationElement, ATT_DESCRIPTION);
        // Read out the category id.
        String categoryId = configurationElement.getAttribute(ATT_CATEGORY_ID);
        if ((categoryId == null) || (categoryId.isEmpty())) {
            categoryId = configurationElement.getAttribute(ATT_CATEGORY);
            if ((categoryId != null) && (categoryId.isEmpty())) {
                categoryId = null;
            }
        }
        // Read out the parameters.
        final Parameter[] parameters = readParameters(configurationElement, warningsToLog, commandManager);
        // Read out the returnTypeId.
        final String returnTypeId = readOptional(configurationElement, ATT_RETURN_TYPE_ID);
        // Read out the help context identifier.
        final String helpContextId = readOptional(configurationElement, ATT_HELP_CONTEXT_ID);
        final Command command = commandManager.getCommand(commandId);
        final Category category = commandManager.getCategory(categoryId);
        if (!category.isDefined()) {
            addWarning(// $NON-NLS-1$
            warningsToLog, // $NON-NLS-1$
            "Commands should really have a category", configurationElement, commandId, "categoryId", // $NON-NLS-1$
            categoryId);
        }
        final ParameterType returnType;
        if (returnTypeId == null) {
            returnType = null;
        } else {
            returnType = commandManager.getParameterType(returnTypeId);
        }
        if (parameters != null && parameters.length > 0) {
            command.undefine();
        }
        if (!command.isDefined()) {
            command.define(name, description, category, parameters, returnType, helpContextId);
            command.setHandler(HandlerServiceImpl.getHandler(commandId));
        }
        readState(configurationElement, warningsToLog, command);
    }
    // If there were any warnings, then log them now.
    logWarnings(warningsToLog, // $NON-NLS-1$
    "Warnings while parsing the commands from the 'org.eclipse.ui.commands' and 'org.eclipse.ui.actionDefinitions' extension points.");
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) ParameterType(org.eclipse.core.commands.ParameterType) Category(org.eclipse.core.commands.Category) Command(org.eclipse.core.commands.Command) ArrayList(java.util.ArrayList) Parameter(org.eclipse.e4.ui.internal.workbench.Parameter) IConfigurationElement(org.eclipse.core.runtime.IConfigurationElement)

Example 15 with Category

use of org.eclipse.core.commands.Category in project eclipse.platform.ui by eclipse-platform.

the class KeysPreferencePage method setVisible.

/**
 * Builds the internal look-up tables before allowing the page to become
 * visible.
 */
@Override
public void setVisible(final boolean visible) {
    if (visible == true) {
        Map<String, Set<Context>> contextsByName = new HashMap<>();
        for (Iterator<String> iterator = contextService.getDefinedContextIds().iterator(); iterator.hasNext(); ) {
            Context context = contextService.getContext(iterator.next());
            try {
                String name = context.getName();
                Set<Context> contexts = contextsByName.get(name);
                if (contexts == null) {
                    contexts = new HashSet<>();
                    contextsByName.put(name, contexts);
                }
                contexts.add(context);
            } catch (final NotDefinedException e) {
            // Do nothing.
            }
        }
        Map<String, Collection<Command>> commandsByName = new HashMap<>();
        for (Iterator<String> iterator = commandService.getDefinedCommandIds().iterator(); iterator.hasNext(); ) {
            Command command = commandService.getCommand(iterator.next());
            if (!isActive(command)) {
                continue;
            }
            try {
                String name = command.getName();
                Collection<Command> commands = commandsByName.get(name);
                if (commands == null) {
                    commands = new HashSet<>();
                    commandsByName.put(name, commands);
                }
                commands.add(command);
            } catch (NotDefinedException eNotDefined) {
            // Do nothing
            }
        }
        // moved here to allow us to remove any empty categories
        commandIdsByCategoryId = new HashMap<>();
        for (Iterator<String> iterator = commandService.getDefinedCommandIds().iterator(); iterator.hasNext(); ) {
            final Command command = commandService.getCommand(iterator.next());
            if (!isActive(command)) {
                continue;
            }
            try {
                String categoryId = command.getCategory().getId();
                Set<String> commandIds = commandIdsByCategoryId.get(categoryId);
                if (commandIds == null) {
                    commandIds = new HashSet<>();
                    commandIdsByCategoryId.put(categoryId, commandIds);
                }
                commandIds.add(command.getId());
            } catch (NotDefinedException eNotDefined) {
            // Do nothing
            }
        }
        Map<String, Set<Category>> categoriesByName = new HashMap<>();
        for (Iterator<String> iterator = commandService.getDefinedCategoryIds().iterator(); iterator.hasNext(); ) {
            Category category = commandService.getCategory(iterator.next());
            try {
                if (commandIdsByCategoryId.containsKey(category.getId())) {
                    String name = category.getName();
                    Set<Category> categories = categoriesByName.get(name);
                    if (categories == null) {
                        categories = new HashSet<>();
                        categoriesByName.put(name, categories);
                    }
                    categories.add(category);
                }
            } catch (NotDefinedException eNotDefined) {
            // Do nothing
            }
        }
        Map<String, Set<Scheme>> schemesByName = new HashMap<>();
        final Scheme[] definedSchemes = bindingService.getDefinedSchemes();
        for (final Scheme scheme : definedSchemes) {
            try {
                String name = scheme.getName();
                Set<Scheme> schemes = schemesByName.get(name);
                if (schemes == null) {
                    schemes = new HashSet<>();
                    schemesByName.put(name, schemes);
                }
                schemes.add(scheme);
            } catch (final NotDefinedException e) {
            // Do nothing.
            }
        }
        contextIdsByUniqueName = new HashMap<>();
        contextUniqueNamesById = new HashMap<>();
        for (Map.Entry<String, Set<Context>> entry : contextsByName.entrySet()) {
            String name = entry.getKey();
            Set<Context> contexts = entry.getValue();
            Iterator<Context> iterator2 = contexts.iterator();
            if (contexts.size() == 1) {
                Context context = iterator2.next();
                contextIdsByUniqueName.put(name, context.getId());
                contextUniqueNamesById.put(context.getId(), name);
            } else {
                while (iterator2.hasNext()) {
                    Context context = iterator2.next();
                    String uniqueName = // $NON-NLS-1$
                    MessageFormat.format(// $NON-NLS-1$
                    Util.translateString(RESOURCE_BUNDLE, "uniqueName"), name, context.getId());
                    contextIdsByUniqueName.put(uniqueName, context.getId());
                    contextUniqueNamesById.put(context.getId(), uniqueName);
                }
            }
        }
        categoryIdsByUniqueName = new HashMap<>();
        categoryUniqueNamesById = new HashMap<>();
        for (Map.Entry<String, Set<Category>> entry : categoriesByName.entrySet()) {
            String name = entry.getKey();
            Set<Category> categories = entry.getValue();
            Iterator<Category> iterator2 = categories.iterator();
            if (categories.size() == 1) {
                Category category = iterator2.next();
                categoryIdsByUniqueName.put(name, category.getId());
                categoryUniqueNamesById.put(category.getId(), name);
            } else {
                while (iterator2.hasNext()) {
                    Category category = iterator2.next();
                    String uniqueName = // $NON-NLS-1$
                    MessageFormat.format(// $NON-NLS-1$
                    Util.translateString(RESOURCE_BUNDLE, "uniqueName"), new Object[] { name, category.getId() });
                    categoryIdsByUniqueName.put(uniqueName, category.getId());
                    categoryUniqueNamesById.put(category.getId(), uniqueName);
                }
            }
        }
        schemeIdsByUniqueName = new HashMap<>();
        schemeUniqueNamesById = new HashMap<>();
        for (Map.Entry<String, Set<Scheme>> entry : schemesByName.entrySet()) {
            String name = entry.getKey();
            Set<Scheme> keyConfigurations = entry.getValue();
            Iterator<Scheme> iterator2 = keyConfigurations.iterator();
            if (keyConfigurations.size() == 1) {
                Scheme scheme = iterator2.next();
                schemeIdsByUniqueName.put(name, scheme.getId());
                schemeUniqueNamesById.put(scheme.getId(), name);
            } else {
                while (iterator2.hasNext()) {
                    Scheme scheme = iterator2.next();
                    String uniqueName = // $NON-NLS-1$
                    MessageFormat.format(// $NON-NLS-1$
                    Util.translateString(RESOURCE_BUNDLE, "uniqueName"), new Object[] { name, scheme.getId() });
                    schemeIdsByUniqueName.put(uniqueName, scheme.getId());
                    schemeUniqueNamesById.put(scheme.getId(), uniqueName);
                }
            }
        }
        Scheme activeScheme = bindingService.getActiveScheme();
        // Make an internal copy of the binding manager, for local changes.
        try {
            for (final Scheme scheme : definedSchemes) {
                final Scheme copy = localChangeManager.getScheme(scheme.getId());
                copy.define(scheme.getName(), scheme.getDescription(), scheme.getParentId());
            }
            localChangeManager.setActiveScheme(bindingService.getActiveScheme());
        } catch (final NotDefinedException e) {
            // $NON-NLS-1$
            throw new Error("There is a programmer error in the keys preference page");
        }
        localChangeManager.setLocale(bindingService.getLocale());
        localChangeManager.setPlatform(bindingService.getPlatform());
        localChangeManager.setBindings(bindingService.getBindings());
        // Populate the category combo box.
        List<String> categoryNames = new ArrayList<>(categoryIdsByUniqueName.keySet());
        categoryNames.sort(Collator.getInstance());
        if (commandIdsByCategoryId.containsKey(null)) {
            // $NON-NLS-1$
            categoryNames.add(0, Util.translateString(RESOURCE_BUNDLE, "other"));
        }
        comboCategory.setItems(categoryNames.toArray(new String[categoryNames.size()]));
        comboCategory.clearSelection();
        comboCategory.deselectAll();
        if (commandIdsByCategoryId.containsKey(null) || !categoryNames.isEmpty()) {
            comboCategory.select(0);
        }
        // Populate the scheme combo box.
        List<String> schemeNames = new ArrayList<>(schemeIdsByUniqueName.keySet());
        schemeNames.sort(Collator.getInstance());
        comboScheme.setItems(schemeNames.toArray(new String[schemeNames.size()]));
        setScheme(activeScheme);
        // Update the entire page.
        update(true);
    }
    super.setVisible(visible);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) Category(org.eclipse.core.commands.Category) Scheme(org.eclipse.jface.bindings.Scheme) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) NotDefinedException(org.eclipse.core.commands.common.NotDefinedException) Context(org.eclipse.core.commands.contexts.Context) ParameterizedCommand(org.eclipse.core.commands.ParameterizedCommand) Command(org.eclipse.core.commands.Command) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

Category (org.eclipse.core.commands.Category)23 Command (org.eclipse.core.commands.Command)14 ParameterizedCommand (org.eclipse.core.commands.ParameterizedCommand)13 ECommandService (org.eclipse.e4.core.commands.ECommandService)10 Test (org.junit.Test)7 NotDefinedException (org.eclipse.core.commands.common.NotDefinedException)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 IParameter (org.eclipse.core.commands.IParameter)5 Context (org.eclipse.core.commands.contexts.Context)4 HashSet (java.util.HashSet)3 IParameterValues (org.eclipse.core.commands.IParameterValues)3 ParameterType (org.eclipse.core.commands.ParameterType)3 IEclipseContext (org.eclipse.e4.core.contexts.IEclipseContext)3 Binding (org.eclipse.jface.bindings.Binding)3 TriggerSequence (org.eclipse.jface.bindings.TriggerSequence)3 CommandManager (org.eclipse.core.commands.CommandManager)2 ExecutionException (org.eclipse.core.commands.ExecutionException)2 IConfigurationElement (org.eclipse.core.runtime.IConfigurationElement)2 IStatus (org.eclipse.core.runtime.IStatus)2