Example usage for org.eclipse.jface.bindings.keys KeySequence format

List of usage examples for org.eclipse.jface.bindings.keys KeySequence format

Introduction

In this page you can find the example usage for org.eclipse.jface.bindings.keys KeySequence format.

Prototype

@Override
public final String format() 

Source Link

Document

Formats this key sequence into the current default look.

Usage

From source file:com.aptana.workbench.commands.EditorCommandsMenuContributor.java

License:Open Source License

/**
 * This recursively builds the menu contribution.
 * //w w w.  j  av  a 2  s. c  o m
 * @param menu
 * @param menusFromScope
 * @param textEditor
 * @param scope
 */
private static void buildMenu(Menu menu, List<MenuElement> menusFromScope, final ITextEditor textEditor,
        String scope, IContributionItem contributionItem) {
    for (MenuElement menuForScope : menusFromScope) {
        if (menuForScope.isHierarchicalMenu()) {
            MenuItem menuItem = new MenuItem(menu, SWT.CASCADE);
            menuItem.setData(contributionItem);
            menuItem.setText(menuForScope.getDisplayName());

            Menu menuForMenuForScope = new Menu(menu);
            menuItem.setMenu(menuForMenuForScope);

            // Recursive
            buildMenu(menuForMenuForScope, menuForScope.getChildren(), textEditor, scope, contributionItem);
        } else if (menuForScope.isSeparator()) {
            MenuItem separatorMenuItem = new MenuItem(menu, SWT.SEPARATOR);
            separatorMenuItem.setData(contributionItem);
        } else {
            final CommandElement command = menuForScope.getCommand();

            // A command attached to the menu item may not be executable on
            // the current platform in which case we skip the menu item
            if (command != null && (!command.isExecutable())) { // FIXME We need to determine if the command applies to the current OS here...
                continue;
            }
            final MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
            menuItem.setData(contributionItem);

            String displayName = menuForScope.getDisplayName();
            String acceleratorText = ""; //$NON-NLS-1$
            if (command != null) {
                KeySequence[] keySequences = KeyBindingUtil.getKeySequences(command);
                if (keySequences != null && keySequences.length > 0) {
                    KeySequence keySequence = keySequences[0];
                    acceleratorText = "\t" + keySequence.format(); //$NON-NLS-1$
                }
                if (command instanceof SnippetElement || keySequences == null || keySequences.length == 0) {
                    String[] triggers = command.getTriggerTypeValues(TriggerType.PREFIX);
                    if (triggers != null && triggers.length > 0) {
                        // Use first trigger
                        displayName += " " + triggers[0] + getTabChar(); //$NON-NLS-1$
                    }
                }
            }
            menuItem.setText(displayName + acceleratorText);
            menuItem.addSelectionListener(new SelectionListener() {
                public void widgetSelected(SelectionEvent e) {
                    if (command == null) {
                        // There is no associated command. Show a message to
                        // the user.
                        MessageDialog.openError(menuItem.getParent().getShell(),
                                Messages.EditorCommandsMenuContributor_TITLE_CommandNotDefined,
                                Messages.bind(Messages.EditorCommandsMenuContributor_MSG_CommandNotDefined,
                                        menuItem.getText()));
                    } else {
                        CommandResult commandResult = CommandExecutionUtils.executeCommand(command,
                                InvocationType.MENU, textEditor);
                        if (commandResult == null) {
                            BundleElement bundle = command.getOwningBundle();
                            String bundleName = (bundle == null) ? "Unknown bundle" : bundle.getDisplayName(); //$NON-NLS-1$
                            IdeLog.logError(WorkbenchPlugin.getDefault(), StringUtil.format(
                                    Messages.EditorCommandsMenuContributor_ErrorExecutingCommandNullResult,
                                    new String[] { command.getDisplayName(), bundleName }));
                        } else {
                            CommandExecutionUtils.processCommandResult(command, commandResult, textEditor);
                        }
                    }
                }

                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });
            // Enable the menu item if:
            // 1. There is no associated command so that we can show a
            // message to the user when they invoke the menu
            // item
            // 2. The command did not specify the scope
            // 3. The command specified the scope and it matches the current
            // scope
            menuItem.setEnabled(
                    command == null || command.getScope() == null || command.getScopeSelector().matches(scope));
        }
    }
    if (menusFromScope.size() > 0) {
        MenuElement menuForScope = menusFromScope.get(0);
        // if we're inside a bundle's main menu
        if (menuForScope.getParent() != null && menuForScope.getParent().getParent() == null) {
            MenuItem separatorMenuItem = new MenuItem(menu, SWT.SEPARATOR);
            separatorMenuItem.setData(contributionItem);

            final MenuItem editBundleItem = new MenuItem(menu, SWT.PUSH);
            editBundleItem.setData(contributionItem);
            editBundleItem.setText(Messages.EditorCommandsMenuContributor_LBL_EditBundle);
            final BundleElement bundleElement = menuForScope.getOwningBundle();
            editBundleItem.addSelectionListener(new SelectionListener() {
                public void widgetSelected(SelectionEvent e) {
                    editBundle(bundleElement);
                }

                public void widgetDefaultSelected(SelectionEvent e) {
                }
            });
        }
    }
}

From source file:com.mulgasoft.emacsplus.commands.KbdMacroBindHandler.java

License:Open Source License

/**
 * Check for C-x C-k <key> binding conflict
 * //from   www .  ja va  2s  . co m
 * @param editor
 * @param c
 * @return IBindingResult with C-x C-k <key> information
 */
private IBindingResult getBinding(ITextEditor editor, char c) {
    IBindingResult result = null;
    try {
        final KeySequence sequence = KeySequence.getInstance(KeySequence.getInstance(STD_KBD_PREFIX),
                KeyStroke.getInstance(c));
        final Binding binding = checkForBinding(editor, sequence);
        result = new IBindingResult() {
            public Binding getKeyBinding() {
                return binding;
            }

            public String getKeyString() {
                return sequence.format();
            }

            public KeySequence getTrigger() {
                return sequence;
            }
        };
    } catch (ParseException e) {
    }
    return result;
}

From source file:org.eclipse.babel.editor.widgets.suggestion.SuggestionBubble.java

License:Open Source License

private void init() {
    // Focus handling simulation for non-Windows systems
    if (!win) {//w w w  .  j av  a2  s.com
        shell.getDisplay().addFilter(SWT.MouseDown, new Listener() {
            @Override
            public void handleEvent(Event event) {

                if (isCursorInsideTextField() && text.getText().length() == 0 && !isCreated()
                        && text.isFocusControl()) {
                    suggestionFilter.setSearchText("");
                    createDialog();
                    tableViewer.refresh();
                } else {
                    if (partialTranslationDialog != null) {
                        if (!partialTranslationDialog.isCursorInsideDialog() && !isCursorInsideDialog()) {
                            dispose();
                        }
                    } else {
                        if (!isCursorInsideDialog()) {
                            dispose();
                        }
                    }
                }
            }
        });
    }

    // shell resize listener to dispose suggestion bubble
    shell.addListener(SWT.Resize, new Listener() {
        public void handleEvent(Event e) {
            if (dialog != null && dialog.getShell() != null) {
                dialog.close();
            }
        }
    });

    // shell move listener
    shell.addListener(SWT.Move, new Listener() {
        public void handleEvent(Event e) {
            if (dialog != null && dialog.getShell() != null) {
                dialog.close();
            }
        }
    });

    // get ScrolledComposite
    ScrolledComposite scrolledComposite = (ScrolledComposite) text.getParent().getParent().getParent()
            .getParent();
    // scroll listener
    scrolledComposite.getVerticalBar().addSelectionListener(new SelectionListener() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (dialog != null && dialog.getShell() != null) {
                dialog.close();
            }
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }

    });

    // ModifyListener
    text.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {

            recalculatePosition();

            if (dialog != null && dialog.getShell() != null && !tableViewer.getControl().isDisposed()) {
                suggestionFilter.setSearchText(text.getText().trim());
                tableViewer.refresh();

                if (tableViewer.getTable().getItemCount() == 0) {
                    if (noSug == null || noSug.isDisposed()) {
                        noSug = new Label(composite, SWT.NONE);
                        noSug.setText("No suggestions available");
                        noSug.moveAbove(tableViewer.getControl());
                        noSug.setBackground(ResourceManager.getColor(255, 255, 225));
                        composite.layout();
                    }
                } else {
                    if (noSug != null && !noSug.isDisposed()) {
                        tableViewer.getTable().setSelection(0);
                        noSug.dispose();
                        composite.layout();
                    }
                }

                suggestionFilter.setSearchText("");
            }
        }

    });

    // KeyListener
    text.addKeyListener(new KeyListener() {

        @Override
        public void keyPressed(KeyEvent e) {
            if ((e.keyCode == SWT.CR || e.keyCode == SWT.LF) && (dialog != null && dialog.getShell() != null)
                    && tableViewer.getTable().getSelectionIndex() != -1) {
                e.doit = false;
            }

            int accelerator = SWTKeySupport.convertEventToUnmodifiedAccelerator(e);
            KeyStroke keyStroke = SWTKeySupport.convertAcceleratorToKeyStroke(accelerator);
            KeySequence sequence = KeySequence.getInstance(keyStroke);

            if (sequence.format().equals(CONTENT_ASSIST)) {

                if (isCreated()) {
                    if (noSug != null && !noSug.isDisposed()) {
                        noSug.dispose();
                        composite.layout();
                    }
                    suggestionFilter.setSearchText("");
                    tableViewer.refresh();
                    tableViewer.getTable().setSelection(0);
                } else {
                    createDialog();
                    suggestionFilter.setSearchText(text.getText().trim());
                    tableViewer.refresh();
                }
                e.doit = false;
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {

            if (dialog == null || dialog.getShell() == null) {
                return;
            }

            if (e.keyCode == SWT.ESC) {
                dialog.close();
                return;
            }

            // Changing selection with keyboard arrows and applying
            // translation with enter
            int currentSelectionIndex = tableViewer.getTable().getSelectionIndex();

            if (e.keyCode == SWT.ARROW_DOWN) {
                if (currentSelectionIndex >= tableViewer.getTable().getItemCount() - 1) {
                    tableViewer.getTable().setSelection(0);
                } else {
                    tableViewer.getTable().setSelection(currentSelectionIndex + 1);
                }
            }

            if (e.keyCode == SWT.ARROW_UP) {
                if (currentSelectionIndex <= 0) {
                    tableViewer.getTable().setSelection(tableViewer.getTable().getItemCount() - 1);
                } else {
                    tableViewer.getTable().setSelection(currentSelectionIndex - 1);
                }
            }

            if (e.keyCode == SWT.CR || e.keyCode == SWT.LF) {
                applySuggestion(text);
            }
        }
    });

    // FocusListener
    text.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(FocusEvent e) {

            if (win && !isCreated() && text.getText().length() == 0) {
                suggestionFilter.setSearchText("");
                createDialog();
                tableViewer.refresh();
            }
        }

        @Override
        public void focusLost(FocusEvent e) {
            if (win && dialog != null && !isCursorInsideDialog()) {
                dialog.close();
            }
        }
    });

    //MouseListener for Windows systems
    if (win) {
        text.addMouseListener(new MouseListener() {

            @Override
            public void mouseDoubleClick(MouseEvent e) {
                // Nothing to do
            }

            @Override
            public void mouseDown(MouseEvent e) {
                // Nothing to do
            }

            @Override
            public void mouseUp(MouseEvent e) {

                if (caret != null) {
                    if (dialog != null && !caret.equals(text.getCaretLocation())) {
                        dialog.close();
                        caret = text.getCaretLocation();
                    }
                } else {
                    caret = text.getCaretLocation();
                }

                if (partialTranslationDialog != null && !partialTranslationDialog.isCursorInsideDialog()) {
                    partialTranslationDialog.dispose();
                }
            }
        });
    }
}

From source file:org.eclipse.e4.ui.keybinding.tests.BindingPersistenceTest.java

License:Open Source License

public final void testBindingTransform() throws Exception {
    ICommandService commandService = (ICommandService) fWorkbench.getAdapter(ICommandService.class);
    IBindingService bindingService = (IBindingService) fWorkbench.getAdapter(IBindingService.class);

    ParameterizedCommand addWS = new ParameterizedCommand(
            commandService.getCommand("org.eclipse.ui.navigate.addToWorkingSet"), null);
    KeySequence m18w = KeySequence.getInstance("M1+8 W");
    KeySequence m28w = KeySequence.getInstance("M2+8 W");
    boolean foundDeleteMarker = false;
    int numOfMarkers = 0;
    Binding[] bindings = bindingService.getBindings();
    for (int i = 0; i < bindings.length; i++) {
        final Binding binding = bindings[i];
        if (binding.getType() == Binding.SYSTEM) {
            String platform = binding.getPlatform();
            int idx = (platform == null ? -1 : platform.indexOf(','));
            assertEquals(binding.toString(), -1, idx);
            if (addWS.equals(binding.getParameterizedCommand())) {
                if (m18w.equals(binding.getTriggerSequence())) {
                    numOfMarkers++;/*from  www.  j a  va  2  s  .com*/
                    assertNull(m18w.format(), binding.getPlatform());
                } else if (m28w.equals(binding.getTriggerSequence())) {
                    numOfMarkers++;
                    assertTrue(platform, Util.WS_CARBON.equals(platform) || Util.WS_COCOA.equals(platform)
                            || Util.WS_GTK.equals(platform) || Util.WS_WIN32.equals(platform));
                }
            } else if (binding.getParameterizedCommand() == null && m18w.equals(binding.getTriggerSequence())) {
                assertTrue(platform, Util.WS_CARBON.equals(platform) || Util.WS_COCOA.equals(platform)
                        || Util.WS_GTK.equals(platform) || Util.WS_WIN32.equals(platform));
                numOfMarkers++;
                foundDeleteMarker = true;
            }
        }
    }
    assertEquals(3, numOfMarkers);
    assertTrue("Unable to find delete marker", foundDeleteMarker);
    TriggerSequence[] activeBindingsFor = bindingService.getActiveBindingsFor(addWS);
    assertEquals(1, activeBindingsFor.length);
}

From source file:org.eclipse.ui.internal.keys.KeyAssistDialog.java

License:Open Source License

/**
 * Returns a string representing the key sequence used to open this dialog.
 *
 * @return the string describing the key sequence, or <code>null</code> if
 *         it cannot be determined.//w ww.  j a  v  a 2s .co m
 */
private String getKeySequenceString() {
    final Command command = commandService.getCommand(IWorkbenchCommandConstants.WINDOW_SHOW_KEY_ASSIST);
    final TriggerSequence[] keyBindings = bindingService
            .getActiveBindingsFor(new ParameterizedCommand(command, null));
    final int keyBindingsCount = keyBindings.length;
    final KeySequence currentState = keyBindingState.getCurrentSequence();
    final int prefixSize = currentState.getKeyStrokes().length;

    // Try to find the first possible matching key binding.
    KeySequence keySequence = null;
    for (int i = 0; i < keyBindingsCount; i++) {
        keySequence = (KeySequence) keyBindings[i];

        // Now just double-check to make sure the key is still possible.
        if (prefixSize > 0) {
            if (keySequence.startsWith(currentState, false)) {
                /*
                 * Okay, so we have a partial match. Replace the key binding
                 * with the required suffix completion.
                 */
                final KeyStroke[] oldKeyStrokes = keySequence.getKeyStrokes();
                final int newSize = oldKeyStrokes.length - prefixSize;
                final KeyStroke[] newKeyStrokes = new KeyStroke[newSize];
                System.arraycopy(oldKeyStrokes, prefixSize, newKeyStrokes, 0, newSize);
                keySequence = KeySequence.getInstance(newKeyStrokes);
                break;
            }

            /*
             * The prefix doesn't match, so null out the key binding and try
             * again.
             */
            keySequence = null;
            continue;

        }

        // There is no prefix, so just grab the first.
        break;
    }
    if (keySequence == null) {
        return null; // couldn't find a suitable key binding
    }
    // RAP [if]: need session aware messages
    //      return NLS.bind(KeyAssistMessages.openPreferencePage, keySequence
    //            .format());
    return NLS.bind(KeyAssistMessages.get().openPreferencePage, keySequence.format());
}

From source file:org.eclipse.ui.tests.keys.BindingPersistenceTest.java

License:Open Source License

public final void testBindingTransform() throws Exception {
    ICommandService commandService = (ICommandService) fWorkbench.getAdapter(ICommandService.class);
    IBindingService bindingService = (IBindingService) fWorkbench.getAdapter(IBindingService.class);

    ParameterizedCommand addWS = new ParameterizedCommand(
            commandService.getCommand("org.eclipse.ui.navigate.addToWorkingSet"), null);
    KeySequence m18w = KeySequence.getInstance("M1+8 W");
    KeySequence m28w = KeySequence.getInstance("M2+8 W");
    boolean foundDeleteMarker = false;
    int numOfMarkers = 0;
    Binding[] bindings = bindingService.getBindings();
    for (int i = 0; i < bindings.length; i++) {
        final Binding binding = bindings[i];
        if (binding.getType() == Binding.SYSTEM) {
            String platform = binding.getPlatform();
            int idx = (platform == null ? -1 : platform.indexOf(','));
            assertEquals(binding.toString(), -1, idx);
            if (addWS.equals(binding.getParameterizedCommand())) {
                if (m18w.equals(binding.getTriggerSequence())) {
                    numOfMarkers++;/* w w  w.ja v  a2s  .c  o  m*/
                    assertNull(m18w.format(), binding.getPlatform());
                } else if (m28w.equals(binding.getTriggerSequence())) {
                    numOfMarkers++;
                    assertTrue(platform, Util.WS_CARBON.equals(platform) || Util.WS_COCOA.equals(platform)
                            || Util.WS_GTK.equals(platform) || Util.WS_WIN32.equals(platform));
                }
            } else if (binding.getParameterizedCommand() == null && m18w.equals(binding.getTriggerSequence())) {
                assertTrue(platform, Util.WS_CARBON.equals(platform) || Util.WS_COCOA.equals(platform)
                        || Util.WS_GTK.equals(platform) || Util.WS_WIN32.equals(platform));
                numOfMarkers++;
                foundDeleteMarker = true;
            }
        }
    }
    assertEquals(3, numOfMarkers);
    assertTrue("Unable to find delete marker", foundDeleteMarker);

    // make sure that the proper contexts are currently active
    IContextService contextService = (IContextService) fWorkbench.getService(IContextService.class);
    contextService.activateContext(IContextService.CONTEXT_ID_DIALOG_AND_WINDOW);
    contextService.activateContext(IContextService.CONTEXT_ID_WINDOW);
    TriggerSequence[] activeBindingsFor = bindingService.getActiveBindingsFor(addWS);
    assertEquals(1, activeBindingsFor.length);
}

From source file:org.elbe.relations.internal.forms.AbstractEditFormTest.java

License:Open Source License

@Test
public void testKeyStrokes() {
    final KeyStroke lKeyStroke = KeyStroke.getInstance(SWT.MOD1, 'I');
    assertEquals(SWT.MOD1 | 'I', lKeyStroke.getModifierKeys() | lKeyStroke.getNaturalKey());
    assertEquals("CTRL+I", lKeyStroke.format());

    final KeySequence lSequence = KeySequence.getInstance(lKeyStroke);

    assertEquals("CTRL+I", lSequence.format());
    assertEquals(SWT.MOD1 | 'I', getKeyCode(lSequence));
}

From source file:org.jboss.tools.common.jdt.debug.ui.preferences.RemoteDebug.java

License:Open Source License

private String format(String sequence) {
    try {/*from   w ww  . j a  v  a 2s .  c  o m*/
        KeySequence keySequence = KeySequence.getInstance(sequence);
        return keySequence.format();
    } catch (ParseException e) {
        RemoteDebugUIActivator.log(e);
        return sequence;
    }
}

From source file:org.python.pydev.debug.ui.actions.RestartLaunchAction.java

License:Open Source License

public void update() {
    IProcess process = console.getProcess();
    setEnabled(true);//from  w  w  w .j  a v a  2  s . c  om
    KeySequence binding = KeyBindingHelper
            .getCommandKeyBinding("org.python.pydev.debug.ui.actions.relaunchLastAction");
    String str = binding != null ? "(" + binding.format() + " when on Pydev editor)" : "(unbinded)";
    if (process.canTerminate()) {
        this.setImageDescriptor(PydevPlugin.getImageCache().getDescriptor(UIConstants.RELAUNCH));
        this.setToolTipText("Restart the current launch. " + str);

    } else {
        this.setImageDescriptor(PydevPlugin.getImageCache().getDescriptor(UIConstants.RELAUNCH1));
        this.setToolTipText("Relaunch with the same configuration." + str);
    }
}

From source file:org.python.pydev.debug.ui.actions.TerminateAllLaunchesAction.java

License:Open Source License

public TerminateAllLaunchesAction() {
    KeySequence binding = KeyBindingHelper
            .getCommandKeyBinding("org.python.pydev.debug.ui.actions.terminateAllLaunchesAction");
    String str = binding != null ? "(" + binding.format() + " when on Pydev editor)" : "(unbinded)";

    this.setImageDescriptor(PydevPlugin.getImageCache().getDescriptor(UIConstants.TERMINATE_ALL));
    this.setToolTipText("Terminate ALL." + str);

    update();/*from  www . j a  v a  2s.c o  m*/
}