Example usage for org.eclipse.jface.bindings.keys KeyStroke getNaturalKey

List of usage examples for org.eclipse.jface.bindings.keys KeyStroke getNaturalKey

Introduction

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

Prototype

public final int getNaturalKey() 

Source Link

Document

Returns the natural key for this key stroke.

Usage

From source file:com.aptana.shared_core.bindings.KeyBindingHelper.java

License:Open Source License

public static boolean matchesKeybinding(int keyCode, int stateMask, KeySequence keySequence) {
    KeyStroke[] keyStrokes = keySequence.getKeyStrokes();

    for (KeyStroke keyStroke : keyStrokes) {

        if (keyStroke.getNaturalKey() == keyCode && ((keyStroke.getModifierKeys() & stateMask) != 0
                || keyStroke.getModifierKeys() == stateMask)) {

            return true;
        }/*from   w w w  .j  a  v  a2s  . c  o m*/
    }
    return false;
}

From source file:com.aptana.ui.keybinding.KeyBindingHelper.java

License:Open Source License

private static boolean internalMatchesKeybinding(int keyCode, int stateMask, TriggerSequence seq) {
    KeySequence keySequence = (KeySequence) seq;
    KeyStroke[] keyStrokes = keySequence.getKeyStrokes();

    if (keyStrokes.length > 1) {
        return false; // Only handling one step binding... the code below does not support things as "CTRL+X R" for
                      // redo.
    }/*w w  w .  j a v  a  2 s.  co  m*/
    for (KeyStroke keyStroke : keyStrokes) {
        if (keyStroke.getNaturalKey() == keyCode && keyStroke.getModifierKeys() == stateMask) {

            return true;
        }
    }
    return false;
}

From source file:com.archimatetool.editor.diagram.actions.FullScreenAction.java

License:Open Source License

/**
 * Add a Key binding mapped to an Action
 *///from  w w w  . j  a v  a 2s .  c o m
private void addKeyBinding(ActionRegistry registry, IBindingService service, ActionFactory actionFactory) {
    KeySequence seq = (KeySequence) service.getBestActiveBindingFor(actionFactory.getCommandId());
    if (seq != null && seq.getKeyStrokes().length > 0) {
        KeyStroke ks = seq.getKeyStrokes()[0];
        keyBindings.add(new KeyBinding(ks.getModifierKeys(), Character.toLowerCase(ks.getNaturalKey()),
                registry.getAction(actionFactory.getId())));
    }
}

From source file:com.github.haixing_hu.swt.action.ActionContributionItemEx.java

License:Open Source License

/**
 * Synchronizes the UI with the given property.
 *
 * @param propertyName//from   www  . j  a va2  s  . com
 *          the name of the property, or <code>null</code> meaning all
 *          applicable properties
 */
@Override
public void update(String propertyName) {
    if (widget != null) {
        // determine what to do
        final boolean textChanged = (propertyName == null) || propertyName.equals(IAction.TEXT);
        boolean imageChanged = (propertyName == null) || propertyName.equals(IAction.IMAGE);
        final boolean tooltipTextChanged = (propertyName == null) || propertyName.equals(IAction.TOOL_TIP_TEXT);
        final boolean enableStateChanged = (propertyName == null) || propertyName.equals(IAction.ENABLED)
                || propertyName.equals(IContributionManagerOverrides.P_ENABLED);
        final boolean checkChanged = ((action.getStyle() == IAction.AS_CHECK_BOX)
                || (action.getStyle() == IAction.AS_RADIO_BUTTON))
                && ((propertyName == null) || propertyName.equals(IAction.CHECKED));

        if (!showImage) {
            //  do not update the image if not show image
            imageChanged = false;
        }
        if (widget instanceof ToolItem) {
            final ToolItem ti = (ToolItem) widget;
            String text = action.getText();
            // the set text is shown only if there is no image or if forced
            // by MODE_FORCE_TEXT
            final boolean showText = (text != null)
                    && (((getMode() & MODE_FORCE_TEXT) != 0) || !hasImages(action));

            // only do the trimming if the text will be used
            if (showText && (text != null)) {
                text = Action.removeAcceleratorText(text);
                text = Action.removeMnemonics(text);
            }

            if (textChanged) {
                final String textToSet = showText ? text : ""; //$NON-NLS-1$
                final boolean rightStyle = (ti.getParent().getStyle() & SWT.RIGHT) != 0;
                if (rightStyle || !ti.getText().equals(textToSet)) {
                    // In addition to being required to update the text if
                    // it
                    // gets nulled out in the action, this is also a
                    // workaround
                    // for bug 50151: Using SWT.RIGHT on a ToolBar leaves
                    // blank space
                    ti.setText(textToSet);
                }
            }

            if (imageChanged) {
                // only substitute a missing image if it has no text
                updateImages(!showText);
            }

            if (tooltipTextChanged || textChanged) {
                String toolTip = action.getToolTipText();
                if ((toolTip == null) || (toolTip.length() == 0)) {
                    toolTip = text;
                }

                final ExternalActionManager.ICallback callback = ExternalActionManager.getInstance()
                        .getCallback();
                final String commandId = action.getActionDefinitionId();
                if ((callback != null) && (commandId != null) && (toolTip != null)) {
                    final String acceleratorText = callback.getAcceleratorText(commandId);
                    if ((acceleratorText != null) && (acceleratorText.length() != 0)) {
                        toolTip = JFaceResources.format("Toolbar_Tooltip_Accelerator", //$NON-NLS-1$
                                new Object[] { toolTip, acceleratorText });
                    }
                }

                // if the text is showing, then only set the tooltip if
                // different
                if (!showText || ((toolTip != null) && !toolTip.equals(text))) {
                    ti.setToolTipText(toolTip);
                } else {
                    ti.setToolTipText(null);
                }
            }

            if (enableStateChanged) {
                final boolean shouldBeEnabled = action.isEnabled() && isEnabledAllowed();

                if (ti.getEnabled() != shouldBeEnabled) {
                    ti.setEnabled(shouldBeEnabled);
                }
            }

            if (checkChanged) {
                final boolean bv = action.isChecked();

                if (ti.getSelection() != bv) {
                    ti.setSelection(bv);
                }
            }
            return;
        }

        if (widget instanceof MenuItem) {
            final MenuItem mi = (MenuItem) widget;

            if (textChanged) {
                int accelerator = 0;
                String acceleratorText = null;
                final ActionEx updatedAction = getAction();
                String text = null;
                accelerator = updatedAction.getAccelerator();
                final ExternalActionManager.ICallback callback = ExternalActionManager.getInstance()
                        .getCallback();

                // Block accelerators that are already in use.
                if ((accelerator != 0) && (callback != null) && (callback.isAcceleratorInUse(accelerator))) {
                    accelerator = 0;
                }

                /*
                 * Process accelerators on GTK in a special way to avoid Bug 42009. We
                 * will override the native input method by allowing these reserved
                 * accelerators to be placed on the menu. We will only do this for
                 * "Ctrl+Shift+[0-9A-FU]".
                 */
                final String commandId = updatedAction.getActionDefinitionId();
                if ((Util.isGtk()) && (callback instanceof IBindingManagerCallback) && (commandId != null)) {
                    final IBindingManagerCallback bindingManagerCallback = (IBindingManagerCallback) callback;
                    final IKeyLookup lookup = KeyLookupFactory.getDefault();
                    final TriggerSequence[] triggerSequences = bindingManagerCallback
                            .getActiveBindingsFor(commandId);
                    for (final TriggerSequence triggerSequence : triggerSequences) {
                        final Trigger[] triggers = triggerSequence.getTriggers();
                        if (triggers.length == 1) {
                            final Trigger trigger = triggers[0];
                            if (trigger instanceof KeyStroke) {
                                final KeyStroke currentKeyStroke = (KeyStroke) trigger;
                                final int currentNaturalKey = currentKeyStroke.getNaturalKey();
                                if ((currentKeyStroke
                                        .getModifierKeys() == (lookup.getCtrl() | lookup.getShift()))
                                        && (((currentNaturalKey >= '0') && (currentNaturalKey <= '9'))
                                                || ((currentNaturalKey >= 'A') && (currentNaturalKey <= 'F'))
                                                || (currentNaturalKey == 'U'))) {
                                    accelerator = currentKeyStroke.getModifierKeys() | currentNaturalKey;
                                    acceleratorText = triggerSequence.format();
                                    break;
                                }
                            }
                        }
                    }
                }

                if (accelerator == 0) {
                    if ((callback != null) && (commandId != null)) {
                        acceleratorText = callback.getAcceleratorText(commandId);
                    }
                }

                IContributionManagerOverrides overrides = null;

                if (getParent() != null) {
                    overrides = getParent().getOverrides();
                }

                if (overrides != null) {
                    text = getParent().getOverrides().getText(this);
                }

                mi.setAccelerator(accelerator);

                if (text == null) {
                    text = updatedAction.getText();
                }

                if ((text != null) && (acceleratorText == null)) {
                    // use extracted accelerator text in case accelerator
                    // cannot be fully represented in one int (e.g.
                    // multi-stroke keys)
                    acceleratorText = LegacyActionTools.extractAcceleratorText(text);
                    if ((acceleratorText == null) && (accelerator != 0)) {
                        acceleratorText = Action.convertAccelerator(accelerator);
                    }
                }

                if (text == null) {
                    text = ""; //$NON-NLS-1$
                } else {
                    text = Action.removeAcceleratorText(text);
                }

                // add "..." if the action will show a dialog
                if (updatedAction.isShowDialog()) {
                    text = text + dialogIndicator;
                }

                if (acceleratorText == null) {
                    mi.setText(text);
                } else {
                    mi.setText(text + '\t' + acceleratorText);
                }
            }

            if (imageChanged) {
                updateImages(false);
            }

            if (enableStateChanged) {
                final boolean shouldBeEnabled = action.isEnabled() && isEnabledAllowed();

                if (mi.getEnabled() != shouldBeEnabled) {
                    mi.setEnabled(shouldBeEnabled);
                }
            }

            if (checkChanged) {
                final boolean bv = action.isChecked();

                if (mi.getSelection() != bv) {
                    mi.setSelection(bv);
                }
            }

            return;
        }

        if (widget instanceof Button) {
            final Button button = (Button) widget;

            if (imageChanged) {
                updateImages(false);
            }

            if (textChanged) {
                String text = action.getText();
                final boolean showText = (text != null)
                        && (((getMode() & MODE_FORCE_TEXT) != 0) || !hasImages(action));
                // only do the trimming if the text will be used
                if (showText) {
                    text = Action.removeAcceleratorText(text);
                }
                final String textToSet = showText ? text : ""; //$NON-NLS-1$
                button.setText(textToSet);
            }

            if (tooltipTextChanged) {
                button.setToolTipText(action.getToolTipText());
            }

            if (enableStateChanged) {
                final boolean shouldBeEnabled = action.isEnabled() && isEnabledAllowed();

                if (button.getEnabled() != shouldBeEnabled) {
                    button.setEnabled(shouldBeEnabled);
                }
            }

            if (checkChanged) {
                final boolean bv = action.isChecked();

                if (button.getSelection() != bv) {
                    button.setSelection(bv);
                }
            }
            return;
        }
    }
}

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

License:Open Source License

/**
 * Does the trigger for this movement command contain the SHIFT key?
 * //from ww w. ja  v  a2 s.  c o m
 * Enforce that the <binding> and <binding>+SHIFT belong to the same Command. 
 * If not, don't apply shift selection (if enabled) for this command (i.e. return false).
 *  
 * @param event the Execution event that invoked this command
 * 
 * @return true if SHIFT modifier was set, else false
 */
private boolean getShifted(ExecutionEvent event) {
    // NB: only single keystroke commands are valid 
    boolean result = false;
    Object trigger = event.getTrigger();
    Event e = null;
    if (trigger != null && trigger instanceof Event && ((e = (Event) trigger).stateMask & SWT.SHIFT) != 0) {
        String cmdId = event.getCommand().getId();
        int mask = (e.stateMask & SWT.MODIFIER_MASK) ^ SWT.SHIFT;
        int u_code = Character.toUpperCase((char) e.keyCode);
        IBindingService bs = (IBindingService) PlatformUI.getWorkbench().getService(IBindingService.class);
        if (cmdId != null && bs != null) {
            TriggerSequence[] sequences = bs.getActiveBindingsFor(cmdId);
            for (TriggerSequence s : sequences) {
                if (s instanceof KeySequence) {
                    KeyStroke[] strokes = ((KeySequence) s).getKeyStrokes();
                    if (strokes.length == 1) {
                        KeyStroke k = strokes[strokes.length - 1];
                        // if keyCode is alpha, then we test uppercase, else keyCode
                        if (k.getModifierKeys() == mask
                                && (k.getNaturalKey() == u_code || k.getNaturalKey() == e.keyCode)) {
                            result = true;
                            break;
                        }
                    }
                }
            }
        }
    }
    return result;
}

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

License:Open Source License

private Event makeEvent(IUniversalResult ua) {
    Event result = new Event();
    KeySequence keys = ua.getTrigger();//from  w w  w.  j  a v a2s  .co  m
    if (keys != null) {
        Trigger[] triggers = keys.getTriggers();
        if (triggers[0] instanceof KeyStroke) { // really, all it can be anyway
            KeyStroke ks = (KeyStroke) triggers[triggers.length - 1];
            result.keyCode = ks.getNaturalKey();
            result.stateMask = ks.getModifierKeys() & SWT.MODIFIER_MASK;
        }
    }
    return result;
}

From source file:com.rcpcompany.test.utils.ui.UITestUtils.java

License:Open Source License

/**
 * Posts the specified keystroke to the specified control which will get focus.
 * /* ww  w. j  av a  2 s .c  o  m*/
 * @param c
 *            the control
 * @param stroke
 *            the text representation of the key-stroke
 */
public static void postKeyStroke(Control c, String stroke) {
    assertNotNull(c);
    assertFalse(c.isDisposed());

    KeyStroke keyStroke = null;
    try {
        keyStroke = KeyStroke.getInstance(stroke);
    } catch (final ParseException ex) {
        fail(stroke + ": " + ex.getMessage());
        return;
    }
    assertTrue(stroke + ": not complete", keyStroke.isComplete());
    // LogUtils.debug(c, stroke + " --> " + keyStroke);

    Event event;

    c.setFocus();

    postModifierKeys(c, keyStroke, true);

    event = new Event();
    event.type = SWT.KeyDown;
    event.stateMask = keyStroke.getModifierKeys();
    event.keyCode = keyStroke.getNaturalKey();
    event.character = (char) event.keyCode;
    event.widget = c;

    // System.out.println("e:: " + ToStringUtils.toString(event));

    assertTrue(stroke + ": post KeyDown", c.getDisplay().post(event));

    event = new Event();
    event.type = SWT.KeyUp;
    event.stateMask = keyStroke.getModifierKeys();
    event.keyCode = keyStroke.getNaturalKey();
    event.character = (char) event.keyCode;
    event.widget = c;

    // System.out.println("e:: " + ToStringUtils.toString(event));

    assertTrue(stroke + ": post KeyUp", c.getDisplay().post(event));

    postModifierKeys(c, keyStroke, false);

    yield();
}

From source file:com.rcpcompany.uibindings.extests.BaseTestUtils.java

License:Open Source License

/**
 * Posts the specified keystroke to the specified control which will get focus.
 * /*from   w  ww.j a  v a2  s .c om*/
 * 
 * @param c the control
 * @param stroke the text representation of the key-stroke
 */
public static void postKeyStroke(Control c, String stroke) {
    KeyStroke keyStroke = null;
    try {
        keyStroke = KeyStroke.getInstance(stroke);
    } catch (final ParseException ex) {
        fail(stroke + ": " + ex.getMessage());
    }
    assertTrue(stroke + ": not complete", keyStroke.isComplete());
    // LogUtils.debug(c, stroke + " --> " + keyStroke);

    Event event;

    c.setFocus();

    postModifierKeys(c, keyStroke, true);

    event = new Event();
    event.type = SWT.KeyDown;
    event.stateMask = keyStroke.getModifierKeys();
    event.keyCode = keyStroke.getNaturalKey();
    event.character = (char) event.keyCode;
    event.widget = c;

    // System.out.println("e:: " + ToStringUtils.toString(event));

    assertTrue(stroke + ": post KeyDown", c.getDisplay().post(event));

    event = new Event();
    event.type = SWT.KeyUp;
    event.stateMask = keyStroke.getModifierKeys();
    event.keyCode = keyStroke.getNaturalKey();
    event.character = (char) event.keyCode;
    event.widget = c;

    // System.out.println("e:: " + ToStringUtils.toString(event));

    assertTrue(stroke + ": post KeyUp", c.getDisplay().post(event));

    postModifierKeys(c, keyStroke, false);

    yield();
}

From source file:de.willuhn.jameica.gui.internal.parts.SearchPart.java

License:Open Source License

/**
 * @see de.willuhn.jameica.gui.Part#paint(org.eclipse.swt.widgets.Composite)
 *///from  w w  w.  jav a  2 s . c  om
public void paint(Composite parent) throws RemoteException {
    this.search = new QueryInput() {

        @Override
        public void doSearch(String query) {
            startSearch();
        }
    };

    this.search.setHint(Application.getI18n().tr("Suche...") + "   (" + this.getKeyStroke().format() + ")");
    this.search.paint(parent);

    GUI.getDisplay().addFilter(SWT.KeyUp, new Listener() {
        public void handleEvent(Event event) {
            KeyStroke ks = getKeyStroke();
            if (ks == null)
                return;

            char c = (char) ks.getNaturalKey();
            if (Character.isLetter(c))
                c = Character.toLowerCase(c);
            if ((event.stateMask == ks.getModifierKeys()) && (event.keyCode == c))
                search.focus();
        }
    });
}

From source file:de.willuhn.jameica.gui.parts.table.FeatureClipboard.java

License:Open Source License

/**
 * Wendet den Shortcut an.// w  w  w. ja va  2s.  c  o  m
 * @param ctx der Context.
 */
protected void applyShortcut(final Context ctx) {
    final String nl = settings.getString("line.separator", System.getProperty("line.separator", "\n"));
    final String sep = settings.getString("col.separator", ";");
    final String quote = settings.getString("quote.char", "\"");

    final KeyStroke shortcut = SWTUtil.getKeyStroke(settings.getString("shortcut", "CTRL+C"));
    if (shortcut == null)
        return;

    this.listener = new Listener() {
        public void handleEvent(org.eclipse.swt.widgets.Event event) {
            char c = (char) shortcut.getNaturalKey();
            if (Character.isLetter(c))
                c = Character.toLowerCase(c);

            if ((event.stateMask == shortcut.getModifierKeys()) && (event.keyCode == c)) {
                Object control = ctx.control;
                if (!(control instanceof Table) && !(control instanceof Tree))
                    return;

                // BUGZILLA 1817 - wenn das Widget nicht Table/Tree ist (sondern Text)
                // dann bearbeitet der User gerade einen Text. In dem Fall duerfen wir
                // auch nicht reagieren, da der User den Text aus dem Edit-Feld kopieren will
                Object widget = event.widget;
                if (!(widget instanceof Table) && !(widget instanceof Tree))
                    return;

                StringBuilder sb = new StringBuilder();

                int colCount = 0;
                int rowCount = 0;

                if (control instanceof Table) {
                    Table t = (Table) control;
                    colCount = t.getColumnCount();
                    TableItem[] rows = t.getSelection();
                    if (rows == null || rows.length == 0)
                        return;

                    rowCount = rows.length;

                    for (TableItem row : rows) {
                        for (int i = 0; i < colCount; ++i) {
                            String s = row.getText(i);
                            sb.append(quote);
                            sb.append(s != null ? s : "");
                            sb.append(quote);
                            if (i + 1 < colCount)
                                sb.append(sep);
                        }
                        sb.append(nl);
                    }
                } else {
                    Tree t = (Tree) control;
                    colCount = t.getColumnCount();
                    TreeItem[] rows = t.getSelection();
                    if (rows == null || rows.length == 0)
                        return;

                    rowCount = rows.length;

                    for (TreeItem row : rows) {
                        for (int i = 0; i < colCount; ++i) {
                            String s = row.getText(i);
                            sb.append(quote);
                            sb.append(s != null ? s : "");
                            sb.append(quote);
                            if (i + 1 < colCount)
                                sb.append(sep);
                        }
                        sb.append(nl);
                    }
                }

                Clipboard clipboard = new Clipboard(GUI.getDisplay());
                TextTransfer transfer = TextTransfer.getInstance();
                clipboard.setContents(new Object[] { sb.toString() }, new Transfer[] { transfer });
                clipboard.dispose();
                Logger.info("copied text to clipboard. cols: " + colCount + ", rows: " + rowCount);
                if (rowCount > 1)
                    Application.getMessagingFactory()
                            .sendMessage(new StatusBarMessage(Application.getI18n()
                                    .tr("{0} Zeilen in Zwischenablage kopiert", Integer.toString(rowCount)),
                                    StatusBarMessage.TYPE_INFO));
                else
                    Application.getMessagingFactory()
                            .sendMessage(new StatusBarMessage(
                                    Application.getI18n().tr("Eine Zeile in Zwischenablage kopiert"),
                                    StatusBarMessage.TYPE_INFO));
            }
        }
    };

    GUI.getDisplay().addFilter(SWT.KeyUp, listener);
    Logger.debug("bound " + listener);
}