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

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

Introduction

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

Prototype

public final String format() 

Source Link

Document

Formats this key stroke into the current default look.

Usage

From source file:bndtools.editor.components.SvcInterfaceSelectionDialog.java

License:Open Source License

@Override
protected Control createDialogArea(Composite parent) {
    Control dialogArea = super.createDialogArea(parent);

    FieldDecoration proposalDecoration = FieldDecorationRegistry.getDefault()
            .getFieldDecoration(FieldDecorationRegistry.DEC_CONTENT_PROPOSAL);

    KeyStroke assistKeyStroke = null;
    try {// w  w w. j  a  va 2s . c o m
        assistKeyStroke = KeyStroke.getInstance("Ctrl+Space");
    } catch (ParseException x) {
        // Ignore
    }

    Text textField = getText();
    ControlDecoration decor = new ControlDecoration(textField, SWT.LEFT | SWT.TOP);
    decor.setImage(proposalDecoration.getImage());
    decor.setDescriptionText(MessageFormat.format(
            "Content Assist is available. Press {0} or start typing to activate", assistKeyStroke.format()));
    decor.setShowHover(true);
    decor.setShowOnlyOnFocus(true);

    SvcInterfaceProposalProvider proposalProvider = new SvcInterfaceProposalProvider(searchContext);
    ContentProposalAdapter proposalAdapter = new ContentProposalAdapter(textField, new TextContentAdapter(),
            proposalProvider, assistKeyStroke, UIConstants.autoActivationCharacters());
    proposalAdapter.addContentProposalListener(proposalProvider);
    proposalAdapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
    proposalAdapter.setLabelProvider(new JavaContentProposalLabelProvider());
    proposalAdapter.setAutoActivationDelay(1500);

    return dialogArea;
}

From source file:bndtools.editor.contents.GeneralInfoPart.java

License:Open Source License

private void createSection(Section section, FormToolkit toolkit) {
    section.setText("Basic Information");

    KeyStroke assistKeyStroke = null;
    try {/*from ww w. j  a va  2s  . c  o m*/
        assistKeyStroke = KeyStroke.getInstance("Ctrl+Space");
    } catch (ParseException x) {
        // Ignore
    }
    FieldDecoration contentAssistDecoration = FieldDecorationRegistry.getDefault()
            .getFieldDecoration(FieldDecorationRegistry.DEC_CONTENT_PROPOSAL);

    Composite composite = toolkit.createComposite(section);
    section.setClient(composite);

    toolkit.createLabel(composite, "Version:");
    txtVersion = toolkit.createText(composite, "", SWT.BORDER);
    ToolTips.setupMessageAndToolTipFromSyntax(txtVersion, Constants.BUNDLE_VERSION);

    Hyperlink linkActivator = toolkit.createHyperlink(composite, "Activator:", SWT.NONE);
    txtActivator = toolkit.createText(composite, "", SWT.BORDER);
    ToolTips.setupMessageAndToolTipFromSyntax(txtActivator, Constants.BUNDLE_ACTIVATOR);

    toolkit.createLabel(composite, "Declarative Services:");
    cmbComponents = new Combo(composite, SWT.READ_ONLY);

    // Content Proposal for the Activator field
    ContentProposalAdapter activatorProposalAdapter = null;

    ActivatorClassProposalProvider proposalProvider = new ActivatorClassProposalProvider();
    activatorProposalAdapter = new ContentProposalAdapter(txtActivator, new TextContentAdapter(),
            proposalProvider, assistKeyStroke, UIConstants.autoActivationCharacters());
    activatorProposalAdapter.addContentProposalListener(proposalProvider);
    activatorProposalAdapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
    activatorProposalAdapter.setLabelProvider(new JavaContentProposalLabelProvider());
    activatorProposalAdapter.setAutoActivationDelay(1000);

    // Decorator for the Activator field
    ControlDecoration decorActivator = new ControlDecoration(txtActivator, SWT.LEFT | SWT.CENTER, composite);
    decorActivator.setImage(contentAssistDecoration.getImage());
    decorActivator.setMarginWidth(3);
    if (assistKeyStroke == null) {
        decorActivator.setDescriptionText("Content Assist is available. Start typing to activate");
    } else {
        decorActivator.setDescriptionText(
                MessageFormat.format("Content Assist is available. Press {0} or start typing to activate",
                        assistKeyStroke.format()));
    }
    decorActivator.setShowOnlyOnFocus(true);
    decorActivator.setShowHover(true);

    // Decorator for the Components combo
    ControlDecoration decorComponents = new ControlDecoration(cmbComponents, SWT.LEFT | SWT.CENTER, composite);
    decorComponents.setImage(FieldDecorationRegistry.getDefault()
            .getFieldDecoration(FieldDecorationRegistry.DEC_INFORMATION).getImage());
    decorComponents.setMarginWidth(3);
    decorComponents.setDescriptionText("Use Java annotations to detect Declarative Service Components.");
    decorComponents.setShowOnlyOnFocus(false);
    decorComponents.setShowHover(true);

    // Listeners
    txtVersion.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent e) {
            lock.ifNotModifying(new Runnable() {
                @Override
                public void run() {
                    addDirtyProperty(Constants.BUNDLE_VERSION);
                }
            });
        }
    });
    cmbComponents.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            lock.ifNotModifying(new Runnable() {
                @Override
                public void run() {
                    ComponentChoice old = componentChoice;

                    int index = cmbComponents.getSelectionIndex();
                    if (index >= 0 && index < ComponentChoice.values().length) {
                        componentChoice = ComponentChoice.values()[cmbComponents.getSelectionIndex()];
                        if (old != componentChoice) {
                            addDirtyProperty(aQute.bnd.osgi.Constants.SERVICE_COMPONENT);
                            addDirtyProperty(aQute.bnd.osgi.Constants.DSANNOTATIONS);
                            if (old == null) {
                                cmbComponents.remove(ComponentChoice.values().length);
                            }
                        }
                    }
                }
            });
        }
    });
    txtActivator.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent ev) {
            lock.ifNotModifying(new Runnable() {
                @Override
                public void run() {
                    addDirtyProperty(Constants.BUNDLE_ACTIVATOR);
                }
            });
        }
    });
    linkActivator.addHyperlinkListener(new HyperlinkAdapter() {
        @Override
        public void linkActivated(HyperlinkEvent ev) {
            String activatorClassName = txtActivator.getText();
            if (activatorClassName != null && activatorClassName.length() > 0) {
                try {
                    IJavaProject javaProject = getJavaProject();
                    if (javaProject == null)
                        return;

                    IType activatorType = javaProject.findType(activatorClassName);
                    if (activatorType != null) {
                        JavaUI.openInEditor(activatorType, true, true);
                    }
                } catch (PartInitException e) {
                    ErrorDialog.openError(getManagedForm().getForm().getShell(), "Error", null,
                            new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0,
                                    MessageFormat.format("Error opening an editor for activator class '{0}'.",
                                            activatorClassName),
                                    e));
                } catch (JavaModelException e) {
                    ErrorDialog.openError(getManagedForm().getForm().getShell(), "Error", null,
                            new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, MessageFormat.format(
                                    "Error searching for activator class '{0}'.", activatorClassName), e));
                }
            }
        }
    });
    activatorProposalAdapter.addContentProposalListener(new IContentProposalListener() {
        @Override
        public void proposalAccepted(IContentProposal proposal) {
            if (proposal instanceof JavaContentProposal) {
                String selectedPackageName = ((JavaContentProposal) proposal).getPackageName();
                if (!model.isIncludedPackage(selectedPackageName)) {
                    model.addPrivatePackage(selectedPackageName);
                }
            }
        }
    });

    // Layout
    GridLayout layout = new GridLayout(2, false);
    layout.horizontalSpacing = 15;

    composite.setLayout(layout);

    GridData gd = new GridData(SWT.FILL, SWT.TOP, true, false);

    txtVersion.setLayoutData(gd);
    txtActivator.setLayoutData(gd);
    cmbComponents.setLayoutData(gd);
}

From source file:bndtools.editor.pkgpatterns.PkgPatternsDetailsPage.java

License:Open Source License

public void createContents(Composite parent) {
    FormToolkit toolkit = getManagedForm().getToolkit();

    FieldDecoration assistDecor = FieldDecorationRegistry.getDefault()
            .getFieldDecoration(FieldDecorationRegistry.DEC_CONTENT_PROPOSAL);
    KeyStroke assistKeyStroke = null;
    try {/*w  w  w .  j a v  a 2  s  .  c  om*/
        assistKeyStroke = KeyStroke.getInstance("Ctrl+Space");
    } catch (ParseException x) {
        // Ignore
    }

    Section mainSection = toolkit.createSection(parent, Section.TITLE_BAR);
    mainSection.setText(title);

    mainComposite = toolkit.createComposite(mainSection);
    mainSection.setClient(mainComposite);

    toolkit.createLabel(mainComposite, "Pattern:");
    txtName = toolkit.createText(mainComposite, "", SWT.BORDER);
    ControlDecoration decPattern = new ControlDecoration(txtName, SWT.LEFT | SWT.TOP, mainComposite);
    decPattern.setImage(assistDecor.getImage());
    decPattern.setDescriptionText(MessageFormat.format(
            "Content assist is available. Press {0} or start typing to activate", assistKeyStroke.format()));
    decPattern.setShowHover(true);
    decPattern.setShowOnlyOnFocus(true);

    PkgPatternsProposalProvider proposalProvider = new PkgPatternsProposalProvider(
            new FormPartJavaSearchContext(this));
    ContentProposalAdapter patternProposalAdapter = new ContentProposalAdapter(txtName,
            new TextContentAdapter(), proposalProvider, assistKeyStroke,
            UIConstants.autoActivationCharacters());
    patternProposalAdapter.addContentProposalListener(proposalProvider);
    patternProposalAdapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_IGNORE);
    patternProposalAdapter.setAutoActivationDelay(1000);
    patternProposalAdapter.setLabelProvider(new PkgPatternProposalLabelProvider());
    patternProposalAdapter.addContentProposalListener(new IContentProposalListener() {
        public void proposalAccepted(IContentProposal proposal) {
            PkgPatternProposal patternProposal = (PkgPatternProposal) proposal;
            String toInsert = patternProposal.getContent();
            int currentPos = txtName.getCaretPosition();
            txtName.setSelection(patternProposal.getReplaceFromPos(), currentPos);
            txtName.insert(toInsert);
            txtName.setSelection(patternProposal.getCursorPosition());
        }
    });

    toolkit.createLabel(mainComposite, "Version:");
    txtVersion = toolkit.createText(mainComposite, "", SWT.BORDER);

    /*
     * Section attribsSection = toolkit.createSection(parent, Section.TITLE_BAR | Section.TWISTIE);
     * attribsSection.setText("Extra Attributes"); Composite attribsComposite =
     * toolkit.createComposite(attribsSection);
     */

    // Listeners
    txtName.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            if (!modifyLock.isUnderModification()) {
                if (selectedClauses.size() == 1) {
                    selectedClauses.get(0).setName(txtName.getText());
                    if (listPart != null) {
                        listPart.updateLabels(selectedClauses);
                        listPart.validate();
                    }
                    markDirty();
                }
            }
        }
    });
    txtVersion.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            if (!modifyLock.isUnderModification()) {
                String text = txtVersion.getText();
                if (text.length() == 0)
                    text = null;

                for (HeaderClause clause : selectedClauses) {
                    clause.getAttribs().put(Constants.VERSION_ATTRIBUTE, text);
                }
                if (listPart != null) {
                    listPart.updateLabels(selectedClauses);
                    listPart.validate();
                }
                markDirty();
            }
        }
    });

    // Layout
    GridData gd;

    parent.setLayout(new GridLayout());
    mainSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    mainComposite.setLayout(new GridLayout(2, false));

    gd = new GridData(SWT.FILL, SWT.TOP, true, false);
    gd.horizontalIndent = 5;
    gd.widthHint = 100;
    txtName.setLayoutData(gd);

    gd = new GridData(SWT.FILL, SWT.TOP, true, false);
    gd.horizontalIndent = 5;
    gd.widthHint = 100;
    txtVersion.setLayoutData(gd);
}

From source file:com.bdaum.zoom.ui.internal.preferences.KeyPreferencePage.java

License:Open Source License

@SuppressWarnings("unused")
private void createDefinitionArea(Composite parent) {
    final Composite composite = new Composite(parent, SWT.NONE);
    composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    composite.setLayout(new GridLayout(2, false));
    new Label(composite, SWT.NONE).setText(Messages.getString("KeyPreferencePage.command2")); //$NON-NLS-1$
    nameField = new Text(composite, SWT.SINGLE | SWT.LEAD | SWT.BORDER | SWT.READ_ONLY);
    nameField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    new Label(composite, SWT.NONE).setText(Messages.getString("KeyPreferencePage.description")); //$NON-NLS-1$
    descriptionField = new Text(composite, SWT.MULTI | SWT.LEAD | SWT.BORDER | SWT.READ_ONLY | SWT.WRAP);
    GridData layoutData = new GridData(SWT.FILL, SWT.CENTER, true, false);
    layoutData.heightHint = 50;//from   ww w .  j ava  2 s  .  c o  m
    descriptionField.setLayoutData(layoutData);
    new Label(composite, SWT.NONE).setText(Messages.getString("KeyPreferencePage.key_sequence")); //$NON-NLS-1$
    Composite keyGroup = new Composite(composite, SWT.NONE);
    keyGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
    GridLayout layout = new GridLayout(2, false);
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    keyGroup.setLayout(layout);
    keyField = new Text(keyGroup, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
    keyField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    keySequenceField = new KeySequenceText(keyField);
    keySequenceField.setKeyStrokeLimit(2);
    keySequenceField.addPropertyChangeListener(new IPropertyChangeListener() {
        public final void propertyChange(final PropertyChangeEvent event) {
            if (!event.getOldValue().equals(event.getNewValue())) {
                final KeySequence keySequence = keySequenceField.getKeySequence();
                if (selectedCommand == null || !keySequence.isComplete())
                    return;
                boolean empty = keySequence.isEmpty();
                Binding newBinding;
                Binding b = commandMap.get(selectedCommand.getId());
                if (b != null) {
                    if (!keySequence.equals(b.getTriggerSequence())) {
                        newBinding = new KeyBinding(keySequence, empty ? null : b.getParameterizedCommand(),
                                activeSchemeId, b.getContextId(), null, null, null, Binding.USER);
                        userMap.remove(b.getTriggerSequence());
                        userMap.put(keySequence, newBinding);
                        if (empty)
                            commandMap.remove(selectedCommand.getId());
                        else
                            commandMap.put(selectedCommand.getId(), newBinding);
                    }
                } else if (!empty) {
                    ParameterizedCommand pc = new ParameterizedCommand(selectedCommand, null);
                    newBinding = new KeyBinding(keySequence, pc, activeSchemeId,
                            "org.eclipse.ui.contexts.window", //$NON-NLS-1$
                            null, null, null, Binding.USER);
                    userMap.put(keySequence, newBinding);
                    commandMap.put(selectedCommand.getId(), newBinding);
                }
                refreshViewer();
                doValidate();
                keyField.setSelection(keyField.getTextLimit());
            }
        }
    });
    final Button helpButton = new Button(keyGroup, SWT.ARROW | SWT.LEFT);
    helpButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
    helpButton.setToolTipText(Messages.getString("KeyPreferencePage.add_a_special_key")); //$NON-NLS-1$
    // Arrow buttons aren't normally added to the tab list. Let's fix that.
    final Control[] tabStops = keyGroup.getTabList();
    final ArrayList<Control> newTabStops = new ArrayList<Control>();
    for (int i = 0; i < tabStops.length; i++) {
        Control tabStop = tabStops[i];
        newTabStops.add(tabStop);
        if (keyField.equals(tabStop))
            newTabStops.add(helpButton);
    }
    keyGroup.setTabList(newTabStops.toArray(new Control[newTabStops.size()]));

    // Construct the menu to attach to the above button.
    final Menu addKeyMenu = new Menu(helpButton);
    final Iterator<?> trappedKeyItr = KeySequenceText.TRAPPED_KEYS.iterator();
    while (trappedKeyItr.hasNext()) {
        final KeyStroke trappedKey = (KeyStroke) trappedKeyItr.next();
        final MenuItem menuItem = new MenuItem(addKeyMenu, SWT.PUSH);
        menuItem.setText(trappedKey.format());
        menuItem.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                keySequenceField.insert(trappedKey);
                keyField.setFocus();
                keyField.setSelection(keyField.getTextLimit());
            }
        });
    }
    helpButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent selectionEvent) {
            Point buttonLocation = helpButton.getLocation();
            buttonLocation = composite.toDisplay(buttonLocation.x, buttonLocation.y);
            Point buttonSize = helpButton.getSize();
            addKeyMenu.setLocation(buttonLocation.x, buttonLocation.y + buttonSize.y);
            addKeyMenu.setVisible(true);
        }
    });
    new Label(composite, SWT.NONE);
    userLabel = new Label(composite, SWT.NONE);
    userLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
}

From source file:de.walware.ecommons.ui.dialogs.QuickTreeInformationControl.java

License:Open Source License

private void initIterateKeys() {
    if (this.commandId == null || this.iterationCount == 1) {
        return;//from w w  w.  j a v a 2 s  .c om
    }
    final IBindingService bindingSvc = (IBindingService) PlatformUI.getWorkbench()
            .getService(IBindingService.class);
    if (bindingSvc == null) {
        return;
    }
    {
        final TriggerSequence sequence = bindingSvc.getBestActiveBindingFor(this.commandId);
        final KeyStroke keyStroke = getKeyStroke(sequence);
        if (keyStroke == null) {
            return;
        }
        this.commandBestKeyStrokeFormatted = keyStroke.format();
    }
    {
        final TriggerSequence[] sequences = bindingSvc.getActiveBindingsFor(this.commandId);
        this.commandActiveKeyStrokes = new ArrayList<KeyStroke>(sequences.length);
        for (int i = 0; i < sequences.length; i++) {
            final KeyStroke keyStroke = getKeyStroke(sequences[i]);
            if (keyStroke != null) {
                this.commandActiveKeyStrokes.add(keyStroke);
            }
        }
    }
    this.commandKeyListener = new KeyAdapter() {
        @Override
        public void keyPressed(final KeyEvent event) {
            final KeyStroke keyStroke = SWTKeySupport
                    .convertAcceleratorToKeyStroke(SWTKeySupport.convertEventToUnmodifiedAccelerator(event));
            for (final KeyStroke activeKeyStroke : QuickTreeInformationControl.this.commandActiveKeyStrokes) {
                if (activeKeyStroke.equals(keyStroke)) {
                    event.doit = false;
                    iterate();
                    return;
                }
            }
        }
    };
}

From source file:de.willuhn.jameica.gui.internal.dialogs.SearchOptionsDialog.java

License:Open Source License

/**
 * @see de.willuhn.jameica.gui.dialogs.AbstractDialog#paint(org.eclipse.swt.widgets.Composite)
 */// w w  w  . j  a  v a  2s . com
protected void paint(Composite parent) throws Exception {
    final I18N i18n = Application.getI18n();

    Container container = new SimpleContainer(parent, true);
    container.addText(i18n.tr("Bitte whlen Sie die Themen, in denen gesucht werden soll:"), true);

    final SearchPart searchPart = GUI.getView().getSearchPart();
    final ShortcutInput shortcut = new ShortcutInput(searchPart.getShortcut());
    shortcut.setName(Application.getI18n().tr("Tastenkrzel fr das Eingabefeld"));
    container.addInput(shortcut);
    final SearchService service = (SearchService) Application.getBootLoader().getBootable(SearchService.class);
    final SearchProvider[] providers = service.getSearchProviders();

    ////////////////////////////////////////////////////////////////////////////
    // Wir muessen die SearchProvider noch nach Plugin gruppieren
    Map<String, List<ProviderObject>> plugins = new HashMap<String, List<ProviderObject>>();
    for (int i = 0; i < providers.length; ++i) {
        ProviderObject o = new ProviderObject(providers[i]);
        String name = (String) o.getAttribute("plugin");

        List<ProviderObject> l = plugins.get(name);
        if (l == null) {
            l = new ArrayList<ProviderObject>();
            plugins.put(name, l);
        }
        l.add(o);
    }
    List<ProviderObject> list = new ArrayList<ProviderObject>();
    Iterator<List<ProviderObject>> it = plugins.values().iterator();
    while (it.hasNext()) {
        list.addAll(it.next());
    }
    ////////////////////////////////////////////////////////////////////////////

    final TablePart table = new TablePart(list, null);
    table.addColumn(i18n.tr("Bezeichnung"), "name");
    table.setCheckable(true);
    table.setMulti(false);
    table.removeFeature(FeatureSummary.class);
    table.setRememberColWidths(true);
    table.setFormatter(new TableFormatter() {

        public void format(TableItem item) {
            if (item == null || item.getData() == null)
                return;

            ProviderObject o = (ProviderObject) item.getData();
            item.setChecked(service.isEnabled(o.provider));
        }
    });

    container.addPart(table);

    ButtonArea buttons = new ButtonArea();
    buttons.addButton(i18n.tr("bernehmen"), new Action() {

        public void handleAction(Object context) throws ApplicationException {
            try {
                // Weil "table.getItems()" nur die ausgewaehlten Provider
                // enthaelt, muessen wir vorher erst alle deaktivieren
                for (int i = 0; i < providers.length; ++i)
                    service.setEnabled(providers[i], false);

                // Jetzt aktivieren wir die, welche selektiert sind
                List selected = table.getItems();
                if (selected != null) {
                    for (int i = 0; i < selected.size(); ++i) {
                        ProviderObject o = (ProviderObject) selected.get(i);
                        service.setEnabled(o.provider, true);
                    }
                }

                KeyStroke ks = (KeyStroke) shortcut.getValue();
                searchPart.setShortcut(ks != null ? ks.format() : null);
            } catch (Exception e) {
                Logger.error("error while applying options", e);
                Application.getMessagingFactory().sendMessage(new StatusBarMessage(
                        i18n.tr("Fehler beim bernehmen der Einstellungen"), StatusBarMessage.TYPE_ERROR));
            }
            Application.getMessagingFactory().sendMessage(
                    new StatusBarMessage(i18n.tr("Einstellungen gespeichert"), StatusBarMessage.TYPE_SUCCESS));
            close();
        }

    }, null, true, "ok.png");
    buttons.addButton(i18n.tr("Abbrechen"), new Action() {
        public void handleAction(Object context) throws ApplicationException {
            close();
        }

    }, null, false, "process-stop.png");

    container.addButtonArea(buttons);
}

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

License:Open Source License

/**
 * Speichert den Shortcut./*from w  w  w  .j  a  v  a 2 s.c  o m*/
 * @param shortcut
 */
public void setShortcut(String shortcut) {
    shortcut = StringUtils.trimToNull(shortcut);
    if (shortcut == null) {
        settings.setAttribute("shortcut", (String) null);
    } else {
        // Checken, ob er sich parsen laesst.
        KeyStroke ks = SWTUtil.getKeyStroke(shortcut);
        if (ks == null)
            Application.getMessagingFactory()
                    .sendMessage(new StatusBarMessage(
                            Application.getI18n().tr("Tastenkombination ungltig: {0}", shortcut),
                            StatusBarMessage.TYPE_ERROR));

        settings.setAttribute("shortcut", ks != null ? ks.format() : null);
    }

    // Forciert das Neu-Laden
    this.currentKey = null;

    // Hint aktualisieren
    if (this.search != null)
        this.search.setHint(Application.getI18n().tr("Suche...") + "   (" + this.getKeyStroke().format() + ")");
}

From source file:org.eclipse.egit.ui.internal.components.BranchNameNormalizer.java

License:Open Source License

/**
 * Creates a new {@link BranchNameNormalizer}.
 *
 * @param text/*w w w .  jav a2  s .  com*/
 *            {@link Text} to operate on
 * @param tooltipText
 *            to show on the bulb decorator
 */
public BranchNameNormalizer(Text text, String tooltipText) {
    KeyStroke stroke = UIUtils
            .getKeystrokeOfBestActiveBindingFor(IWorkbenchCommandConstants.EDIT_CONTENT_ASSIST);
    if (stroke == null) {
        stroke = KeyStroke.getInstance(SWT.MOD1, ' ');
    }
    decorator = UIUtils.addBulbDecorator(text, MessageFormat.format(tooltipText, stroke.format()));
    decorator.hide();
    ContentProposalAdapter proposer = new ContentProposalAdapter(text, new TextContentAdapter(), (c, p) -> {
        if (c.isEmpty() || Repository.isValidRefName(Constants.R_HEADS + c)) {
            return null;
        }
        String normalized = Repository.normalizeBranchName(c);
        if (normalized == null || normalized.isEmpty()) {
            return new ContentProposal[0];
        }
        return new ContentProposal[] { new ContentProposal(normalized) };
    }, stroke, BRANCH_NAME_NORMALIZER_ACTIVATION_CHARS);
    proposer.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
    text.addVerifyListener(e -> e.text = e.text.replaceAll(REGEX_BLANK, UNDERSCORE));
    text.addModifyListener(e -> {
        String input = text.getText();
        boolean doProposeCorrection = !input.isEmpty() && !Repository.isValidRefName(Constants.R_HEADS + input);
        setVisible(doProposeCorrection);
    });
}

From source file:org.eclipse.egit.ui.internal.fetch.FetchGerritChangePage.java

License:Open Source License

private void addRefContentProposalToText(final Text textField) {
    KeyStroke stroke;
    try {/*w ww  . j  av a  2 s. c om*/
        stroke = KeyStroke.getInstance("CTRL+SPACE"); //$NON-NLS-1$
        UIUtils.addBulbDecorator(textField,
                NLS.bind(UIText.FetchGerritChangePage_ContentAssistTooltip, stroke.format()));
    } catch (ParseException e1) {
        Activator.handleError(e1.getMessage(), e1, false);
        stroke = null;
    }

    IContentProposalProvider cp = new IContentProposalProvider() {
        public IContentProposal[] getProposals(String contents, int position) {
            List<IContentProposal> resultList = new ArrayList<IContentProposal>();

            // make the simplest possible pattern check: allow "*"
            // for multiple characters
            String patternString = contents;
            // ignore spaces in the beginning
            while (patternString.length() > 0 && patternString.charAt(0) == ' ')
                patternString = patternString.substring(1);

            // we quote the string as it may contain spaces
            // and other stuff colliding with the Pattern
            patternString = Pattern.quote(patternString);

            patternString = patternString.replaceAll("\\x2A", ".*"); //$NON-NLS-1$ //$NON-NLS-2$

            // make sure we add a (logical) * at the end
            if (!patternString.endsWith(".*")) //$NON-NLS-1$
                patternString = patternString + ".*"; //$NON-NLS-1$

            // let's compile a case-insensitive pattern (assumes ASCII only)
            Pattern pattern;
            try {
                pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
            } catch (PatternSyntaxException e) {
                pattern = null;
            }

            List<Change> proposals;
            try {
                proposals = getRefsForContentAssist();
            } catch (InvocationTargetException e) {
                Activator.handleError(e.getMessage(), e, false);
                return null;
            } catch (InterruptedException e) {
                return null;
            }

            if (proposals != null)
                for (final Change ref : proposals) {
                    if (pattern != null && !pattern.matcher(ref.getChangeNumber().toString()).matches())
                        continue;
                    IContentProposal propsal = new ChangeContentProposal(ref);
                    resultList.add(propsal);
                }

            return resultList.toArray(new IContentProposal[resultList.size()]);
        }
    };

    ContentProposalAdapter adapter = new ContentProposalAdapter(textField, new TextContentAdapter(), cp, stroke,
            null);
    // set the acceptance style to always replace the complete content
    adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
}

From source file:org.eclipse.egit.ui.internal.gerrit.GerritConfigurationPage.java

License:Open Source License

private void addRefContentProposalToText(final Text textField) {
    KeyStroke stroke;
    try {/*from  www.j av  a 2  s .co m*/
        stroke = KeyStroke.getInstance("CTRL+SPACE"); //$NON-NLS-1$
        UIUtils.addBulbDecorator(textField,
                NLS.bind(UIText.GerritConfigurationPage_BranchTooltipHover, stroke.format()));
    } catch (ParseException e1) {
        Activator.handleError(e1.getMessage(), e1, false);
        stroke = null;
    }

    IContentProposalProvider cp = new IContentProposalProvider() {
        public IContentProposal[] getProposals(String contents, int position) {
            List<IContentProposal> resultList = new ArrayList<IContentProposal>();

            // make the simplest possible pattern check: allow "*"
            // for multiple characters
            String patternString = contents;
            // ignore spaces in the beginning
            while (patternString.length() > 0 && patternString.charAt(0) == ' ') {
                patternString = patternString.substring(1);
            }

            // we quote the string as it may contain spaces
            // and other stuff colliding with the Pattern
            patternString = Pattern.quote(patternString);

            patternString = patternString.replaceAll("\\x2A", ".*"); //$NON-NLS-1$ //$NON-NLS-2$

            // make sure we add a (logical) * at the end
            if (!patternString.endsWith(".*")) //$NON-NLS-1$
                patternString = patternString + ".*"; //$NON-NLS-1$

            // let's compile a case-insensitive pattern (assumes ASCII only)
            Pattern pattern;
            try {
                pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
            } catch (PatternSyntaxException e) {
                pattern = null;
            }

            Set<String> proposals = new TreeSet<String>();

            try {
                // propose the names of the remote tracking
                // branches for the given remote
                Set<String> remotes = repository.getRefDatabase()
                        .getRefs(Constants.R_REMOTES + remoteName + "/").keySet(); //$NON-NLS-1$
                proposals.addAll(remotes);
            } catch (IOException e) {
                // simply ignore, no proposals then
            }

            for (final String proposal : proposals) {
                if (pattern != null && !pattern.matcher(proposal).matches())
                    continue;
                IContentProposal propsal = new BranchContentProposal(proposal);
                resultList.add(propsal);
            }

            return resultList.toArray(new IContentProposal[resultList.size()]);
        }
    };

    ContentProposalAdapter adapter = new ContentProposalAdapter(textField, new TextContentAdapter(), cp, stroke,
            null);
    // set the acceptance style to always replace the complete content
    adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
}