Example usage for org.eclipse.jface.dialogs IDialogConstants HORIZONTAL_MARGIN

List of usage examples for org.eclipse.jface.dialogs IDialogConstants HORIZONTAL_MARGIN

Introduction

In this page you can find the example usage for org.eclipse.jface.dialogs IDialogConstants HORIZONTAL_MARGIN.

Prototype

int HORIZONTAL_MARGIN

To view the source code for org.eclipse.jface.dialogs IDialogConstants HORIZONTAL_MARGIN.

Click Source Link

Document

Horizontal margin in dialog units (value 7).

Usage

From source file:org.eclipse.equinox.p2.ui.RepositoryManipulationPage.java

License:Open Source License

protected Control createContents(Composite parent) {
    display = parent.getDisplay();// w w w  .ja v  a 2  s.  c o  m
    // The help refers to the full-blown dialog.  No help if it's read only.
    if (policy.getRepositoriesVisible())
        PlatformUI.getWorkbench().getHelpSystem().setHelp(parent.getShell(),
                IProvHelpContextIds.REPOSITORY_MANIPULATION_DIALOG);

    Composite composite = new Composite(parent, SWT.NONE);
    GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
    composite.setLayoutData(gd);

    GridLayout layout = new GridLayout();
    layout.numColumns = policy.getRepositoriesVisible() ? 2 : 1;
    layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
    layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
    composite.setLayout(layout);

    // Filter box
    pattern = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.SEARCH | SWT.CANCEL);
    pattern.getAccessible().addAccessibleListener(new AccessibleAdapter() {
        public void getName(AccessibleEvent e) {
            e.result = DEFAULT_FILTER_TEXT;
        }
    });
    pattern.setText(DEFAULT_FILTER_TEXT);
    pattern.selectAll();
    pattern.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            applyFilter();
        }
    });

    pattern.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            if (e.keyCode == SWT.ARROW_DOWN) {
                if (table.getItemCount() > 0) {
                    table.setFocus();
                } else if (e.character == SWT.CR) {
                    return;
                }
            }
        }
    });

    pattern.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent e) {
            display.asyncExec(new Runnable() {
                public void run() {
                    if (!pattern.isDisposed()) {
                        if (DEFAULT_FILTER_TEXT.equals(pattern.getText().trim())) {
                            pattern.selectAll();
                        }
                    }
                }
            });
        }
    });
    gd = new GridData(SWT.FILL, SWT.FILL, true, false);
    pattern.setLayoutData(gd);

    // spacer to fill other column
    if (policy.getRepositoriesVisible())
        new Label(composite, SWT.NONE);

    // Table of available repositories
    table = new Table(composite,
            SWT.CHECK | SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
    repositoryViewer = new CheckboxTableViewer(table);

    // Key listener for delete
    table.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            if (e.keyCode == SWT.DEL) {
                removeRepositories();
            }
        }
    });
    setTableColumns();
    CopyUtils.activateCopy(this, table);

    repositoryViewer.setComparer(new ProvElementComparer());
    comparator = new MetadataRepositoryElementComparator(RepositoryDetailsLabelProvider.COL_NAME);
    repositoryViewer.setComparator(comparator);
    filter = new MetadataRepositoryPatternFilter();
    repositoryViewer.setFilters(new ViewerFilter[] { filter });
    // We don't need a deferred content provider because we are caching local results before
    // actually querying
    repositoryViewer.setContentProvider(new ProvElementContentProvider());
    labelProvider = new RepositoryDetailsLabelProvider();
    repositoryViewer.setLabelProvider(labelProvider);

    // Edit the nickname
    repositoryViewer.setCellModifier(new ICellModifier() {
        public boolean canModify(Object element, String property) {
            return element instanceof MetadataRepositoryElement;
        }

        public Object getValue(Object element, String property) {
            return ((MetadataRepositoryElement) element).getName();
        }

        public void modify(Object element, String property, Object value) {
            if (value != null && value.toString().length() >= 0) {
                MetadataRepositoryElement repo;
                if (element instanceof Item) {
                    repo = (MetadataRepositoryElement) ((Item) element).getData();
                } else if (element instanceof MetadataRepositoryElement) {
                    repo = (MetadataRepositoryElement) element;
                } else {
                    return;
                }
                if (!value.toString().equals(repo.getName())) {
                    changed = true;
                    repo.setNickname(value.toString());
                    if (comparator.getSortKey() == RepositoryDetailsLabelProvider.COL_NAME)
                        repositoryViewer.refresh(true);
                    else
                        repositoryViewer.update(repo, null);
                }
            }
        }

    });
    repositoryViewer.setColumnProperties(new String[] { "nickname" }); //$NON-NLS-1$
    repositoryViewer.setCellEditors(new CellEditor[] { new TextCellEditor(repositoryViewer.getTable()) });

    repositoryViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            if (policy.getRepositoriesVisible())
                validateButtons();
            setDetails();
        }
    });

    repositoryViewer.setCheckStateProvider(new ICheckStateProvider() {
        public boolean isChecked(Object element) {
            return ((MetadataRepositoryElement) element).isEnabled();
        }

        public boolean isGrayed(Object element) {
            return false;
        }
    });

    repositoryViewer.addCheckStateListener(new ICheckStateListener() {
        public void checkStateChanged(CheckStateChangedEvent event) {
            MetadataRepositoryElement element = (MetadataRepositoryElement) event.getElement();
            element.setEnabled(event.getChecked());
            // paranoid that an equal but not identical element was passed in as the selection.
            // update the cache map just in case.
            getInput().put(element);
            // update the viewer to show the change
            updateForEnablementChange(new MetadataRepositoryElement[] { element });
        }
    });

    // Input last
    repositoryViewer.setInput(getInput());

    GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
    data.widthHint = convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_WIDTH);
    data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT);
    table.setLayoutData(data);

    // Drop targets and vertical buttons only if repository manipulation is provided.
    if (policy.getRepositoriesVisible()) {
        DropTarget target = new DropTarget(table, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK);
        target.setTransfer(new Transfer[] { URLTransfer.getInstance(), FileTransfer.getInstance() });
        target.addDropListener(new RepositoryManipulatorDropTarget(ui, table));

        // Vertical buttons
        Composite verticalButtonBar = createVerticalButtonBar(composite);
        data = new GridData(SWT.FILL, SWT.FILL, false, false);
        data.verticalAlignment = SWT.TOP;
        data.verticalIndent = 0;
        verticalButtonBar.setLayoutData(data);
        listener = getViewerProvisioningListener();

        ProvUI.getProvisioningEventBus(ui.getSession()).addListener(listener);
        composite.addDisposeListener(new DisposeListener() {
            public void widgetDisposed(DisposeEvent event) {
                ProvUI.getProvisioningEventBus(ui.getSession()).removeListener(listener);
            }
        });

        validateButtons();
    }

    // Details area
    details = new Text(composite, SWT.READ_ONLY | SWT.WRAP);
    data = new GridData(SWT.FILL, SWT.FILL, true, false);
    data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_SITEDETAILS_HEIGHT);

    details.setLayoutData(data);

    Dialog.applyDialogFont(composite);
    return composite;
}

From source file:org.eclipse.gef4.fx.jface.FXPaintSelectionDialog.java

License:Open Source License

@Override
protected Control createDialogArea(Composite parent) {
    Composite container = (Composite) super.createDialogArea(parent);
    container.setBackground(parent.getBackground());
    container.setFont(parent.getFont());
    GridLayout gl = new GridLayout(1, true);
    gl.marginHeight = 0;//w w w  .j ava 2 s  .  c  o  m
    gl.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    gl.marginTop = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
    container.setLayout(gl);

    Composite labelContainer = new Composite(container, SWT.NONE);
    labelContainer.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
    gl = new GridLayout(2, true);
    gl.marginWidth = 3; // align with combo below
    labelContainer.setLayout(gl);
    Label fillLabel = new Label(labelContainer, SWT.LEFT);
    fillLabel.setBackground(parent.getBackground());
    fillLabel.setFont(parent.getFont());
    fillLabel.setLayoutData(new GridData());
    fillLabel.setText("Fill:");
    imageLabel = new Label(labelContainer, SWT.RIGHT);
    imageLabel.setLayoutData(new GridData(SWT.END, SWT.TOP, true, false));

    Composite optionsContainer = new Composite(container, SWT.NONE);
    optionsContainer.setBackground(parent.getBackground());
    optionsContainer.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
    gl = new GridLayout(1, true);
    gl.marginWidth = 3; // align with combo above
    optionsContainer.setLayout(gl);

    optionsCombo = new Combo(optionsContainer, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER);
    optionsCombo
            .setItems(new String[] { "No Fill", "Color Fill", "Gradient Fill", "Advanced Gradient Fill"/*
                                                                                                       * , "Image Fill"
                                                                                                       */ });
    optionsCombo.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));

    final Composite optionsComposite = new Composite(optionsContainer, SWT.NONE);
    optionsComposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
    optionsComposite.setBackground(parent.getBackground());
    final StackLayout sl = new StackLayout();

    optionsComposite.setLayout(sl);

    // no fill
    final Control noFillControl = new Composite(optionsComposite, SWT.NONE);
    final Control colorFillControl = createColorFillControl(optionsComposite);
    final Control simpleGradientFillControl = createSimpleGradientFillControl(optionsComposite);
    final Control advancedGradientFillControl = createAdvancedGradientFillControl(optionsComposite);
    // TODO: others

    optionsCombo.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            // store previous option value
            if (paint != null) {
                if (paint instanceof Color && !Color.TRANSPARENT.equals(paint)) {
                    lastFillColor = paint;
                } else if (FXSimpleLinearGradientPicker.isSimpleLinearGradient(paint)) {
                    lastSimpleGradient = paint;
                } else if (FXAdvancedLinearGradientPicker.isAdvancedLinearGradient(paint)) {
                    lastAdvancedGradient = paint;
                }
            }
            // set new option value
            switch (optionsCombo.getSelectionIndex()) {
            case 0:
                sl.topControl = noFillControl;
                paint = Color.TRANSPARENT;
                break;
            case 1:
                sl.topControl = colorFillControl;
                setPaint(lastFillColor); // restore last fill color
                colorPicker.setColor((Color) paint);
                break;
            case 2:
                sl.topControl = simpleGradientFillControl;
                setPaint(lastSimpleGradient);
                simpleGradientPicker.setSimpleLinearGradient((LinearGradient) paint);
                break;
            case 3:
                sl.topControl = advancedGradientFillControl;
                setPaint(lastAdvancedGradient);
                advancedGradientPicker.setAdvancedGradient((LinearGradient) paint);
                break;
            default:
                throw new IllegalArgumentException("Unsupported option");
            }
            updateImageLabel();
            optionsComposite.layout();
        }

    });

    if (Color.TRANSPARENT.equals(paint)) {
        optionsCombo.select(0);
    } else if (paint instanceof Color) {
        optionsCombo.select(1);
    } else if (FXSimpleLinearGradientPicker.isSimpleLinearGradient(paint)) {
        optionsCombo.select(2);
    } else if (FXAdvancedLinearGradientPicker.isAdvancedLinearGradient(paint)) {
        optionsCombo.select(3);
    } else if (paint instanceof ImagePattern) {
        optionsCombo.select(4);
    }
    return container;
}

From source file:org.eclipse.gmf.internal.graphdef.codegen.ui.FigureGeneratorOptionsDialog.java

License:Open Source License

protected Control createDialogArea(Composite parent) {
    Composite result = (Composite) super.createDialogArea(parent);
    GridLayout layout = new GridLayout();
    layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
    layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
    result.setLayout(layout);//from   w  ww. ja v a  2 s  .co m
    createControls(result);
    setTitle("Generator Model Options");
    warnLiteVerstionDoesNotSupportMapMode();
    Dialog.applyDialogFont(result);
    return result;
}

From source file:org.eclipse.gmf.runtime.emf.ui.preferences.NewPathVariableDialog.java

License:Open Source License

protected Control createDialogArea(Composite parent) {
    Composite result = (Composite) super.createDialogArea(parent);

    initializeDialogUnits(result);//from  w  w  w.j a  v  a 2 s.  c om

    Composite composite = new Composite(result, SWT.NONE);
    composite.setLayout(new GridLayout(3, false));
    GridData data = null;
    data = new GridData(GridData.FILL_BOTH);
    data.grabExcessHorizontalSpace = true;
    data.grabExcessHorizontalSpace = true;
    data.horizontalIndent = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    data.verticalIndent = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
    composite.setLayoutData(data);

    Label label = new Label(composite, SWT.LEFT);
    label.setText(EMFUIMessages.PathVariableDialog_nameLabel);
    data = new GridData(SWT.BEGINNING);
    label.setLayoutData(data);

    nameText = new Text(composite, SWT.BORDER);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.grabExcessHorizontalSpace = true;
    nameText.setLayoutData(data);
    if (initialName != null) {
        nameText.setText(initialName);
    }

    // blank to occupy the upper-right corner
    new Label(composite, SWT.None);

    label = new Label(composite, SWT.NONE);
    label.setText(EMFUIMessages.PathVariableDialog_locationLabel);
    data = new GridData(SWT.BEGINNING);
    label.setLayoutData(data);

    // force left-to-right orientation because file paths are always LTR
    locationText = new Text(composite, SWT.BORDER | SWT.LEFT_TO_RIGHT);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.grabExcessHorizontalSpace = true;
    locationText.setLayoutData(data);
    if (initialLocation != null) {
        locationText.setText(initialLocation);
    }

    Button browseButton = new Button(composite, SWT.PUSH);
    browseButton.setText(EMFUIMessages.PathVariableDialog_browseButton);
    setButtonLayoutData(browseButton);

    browseButton.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent e) {
            DirectoryDialog dlg = new DirectoryDialog(getShell());
            dlg.setText(EMFUIMessages.PathVariableDialog_browseDialogTitle);
            dlg.setMessage(EMFUIMessages.PathVariableDialog_browseDialogMessage);

            String folder = dlg.open();
            if (folder != null) {
                locationText.setText(folder);
            }
        }
    });

    ModifyListener l = new ModifyListener() {

        public void modifyText(ModifyEvent e) {
            validateInputs();
        }
    };

    nameText.addModifyListener(l);
    locationText.addModifyListener(l);

    if (initialName != null) {
        // edit mode
        setTitle(EMFUIMessages.PathVariableDialog_editTitle);

        // select the location field text and set focus to it
        locationText.setSelection(0, locationText.getText().length());
        locationText.setFocus();
    } else {
        // new mode
        setTitle(EMFUIMessages.PathVariableDialog_newTitle);
    }

    setMessage(plainMsg);

    return result;
}

From source file:org.eclipse.gyrex.admin.ui.internal.widgets.SelectionStatusDialog.java

License:Open Source License

@Override
protected Control createButtonBar(final Composite parent) {
    final Font font = parent.getFont();
    final Composite composite = new Composite(parent, SWT.NULL);
    final GridLayout layout = new GridLayout();
    if (!fStatusLineAboveButtons) {
        layout.numColumns = 2;/*w  w  w  . j a  va  2s .c  o  m*/
    }
    layout.marginHeight = 0;
    layout.marginLeft = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    layout.marginWidth = 0;
    composite.setLayout(layout);
    composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    composite.setFont(font);

    if (!fStatusLineAboveButtons && isHelpAvailable()) {
        createHelpControl(composite);
    }
    fStatusLine = new MessageLine(composite);
    fStatusLine.setAlignment(SWT.LEFT);
    final GridData statusData = new GridData(GridData.FILL_HORIZONTAL);
    fStatusLine.setErrorStatus(null);
    fStatusLine.setFont(font);
    if (fStatusLineAboveButtons && isHelpAvailable()) {
        statusData.horizontalSpan = 2;
        createHelpControl(composite);
    }
    fStatusLine.setLayoutData(statusData);

    /*
     * Create the rest of the button bar, but tell it not to
     * create a help button (we've already created it).
     */
    final boolean helpAvailable = isHelpAvailable();
    setHelpAvailable(false);
    super.createButtonBar(composite);
    setHelpAvailable(helpAvailable);
    return composite;
}

From source file:org.eclipse.jdt.internal.ui.wizards.buildpaths.newsourcepage.LinkFolderDialog.java

License:Open Source License

protected Control createDialogArea(Composite parent) {
    initializeDialogUnits(parent);//  w w w.j a  v a 2 s. c o  m

    int numOfColumns = 3;
    Composite composite = new Composite(parent, SWT.NONE);
    composite.setFont(parent.getFont());

    GridLayout layout = new GridLayout(numOfColumns, false);
    layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
    layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    composite.setLayout(layout);
    GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
    gridData.minimumWidth = convertWidthInCharsToPixels(80);
    composite.setLayoutData(gridData);

    Label label = new Label(composite, SWT.NONE);
    label.setFont(composite.getFont());
    label.setText(Messages.format(NewWizardMessages.LinkFolderDialog_createIn,
            BasicElementLabels.getPathLabel(fContainer.getFullPath(), false)));
    label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, numOfColumns, 1));

    fDependenciesGroup = new LinkFields(composite, numOfColumns);
    if (fTarget != null) {
        fDependenciesGroup.setLinkTarget(fTarget);
    }
    fFolderNameField = new FolderNameField(composite, numOfColumns);
    if (fName != null) {
        fFolderNameField.setText(fName);
    }

    Validator validator = new Validator();
    fDependenciesGroup.addObserver(validator);
    fFolderNameField.addObserver(validator);

    return composite;
}

From source file:org.eclipse.jsch.internal.ui.preference.ExportDialog.java

License:Open Source License

protected Control createDialogArea(Composite parent) {
    initializeDialogUnits(parent);//  ww w.  j  av a2  s .co m
    Composite main = new Composite(parent, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.numColumns = 2;
    layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
    layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
    main.setLayout(layout);
    main.setLayoutData(new GridData(GridData.FILL_BOTH));

    if (message != null) {
        Label messageLabel = new Label(main, SWT.WRAP);
        messageLabel.setText(message);
        GridData data = new GridData(GridData.FILL_HORIZONTAL);
        data.horizontalSpan = 2;
        messageLabel.setLayoutData(data);
    }

    createTargetFields(main);
    Dialog.applyDialogFont(main);
    return main;
}

From source file:org.eclipse.jsch.internal.ui.preference.PassphraseDialog.java

License:Open Source License

protected Control createDialogArea(Composite parent) {
    initializeDialogUnits(parent);//from ww w .  j av  a 2  s. c  om
    Composite main = new Composite(parent, SWT.NONE);

    GridLayout layout = new GridLayout();
    layout.numColumns = 3;
    layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
    layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
    main.setLayout(layout);
    main.setLayoutData(new GridData(GridData.FILL_BOTH));

    if (message != null) {
        Label messageLabel = new Label(main, SWT.WRAP);
        messageLabel.setText(message);
        GridData data = new GridData(GridData.FILL_HORIZONTAL);
        data.horizontalSpan = 3;
        messageLabel.setLayoutData(data);
    }

    createPassphraseFields(main);
    Dialog.applyDialogFont(main);
    return main;
}

From source file:org.eclipse.jsch.internal.ui.preference.PreferencePage.java

License:Open Source License

private Control createGeneralPage(Composite parent) {
    Composite group = new Composite(parent, SWT.NULL);
    GridLayout layout = new GridLayout();
    layout.numColumns = 3;/*from w  ww  . j ava  2 s.  co m*/
    layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
    layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
    group.setLayout(layout);
    GridData data = new GridData();
    data.horizontalAlignment = GridData.FILL;
    group.setLayoutData(data);

    ssh2HomeLabel = new Label(group, SWT.NONE);
    ssh2HomeLabel.setText(Messages.CVSSSH2PreferencePage_23);

    ssh2HomeText = new Text(group, SWT.SINGLE | SWT.BORDER);
    ssh2HomeText.setFont(group.getFont());
    GridData gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 1;
    ssh2HomeText.setLayoutData(gd);

    ssh2HomeBrowse = new Button(group, SWT.NULL);
    ssh2HomeBrowse.setText(Messages.CVSSSH2PreferencePage_24);
    gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    gd.horizontalSpan = 1;
    ssh2HomeBrowse.setLayoutData(gd);

    createSpacer(group, 3);

    privateKeyLabel = new Label(group, SWT.NONE);
    privateKeyLabel.setText(Messages.CVSSSH2PreferencePage_25);

    privateKeyText = new Text(group, SWT.SINGLE | SWT.BORDER);
    privateKeyText.setFont(group.getFont());
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 1;
    privateKeyText.setLayoutData(gd);

    privateKeyAdd = new Button(group, SWT.NULL);
    privateKeyAdd.setText(Messages.CVSSSH2PreferencePage_26);
    gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    gd.horizontalSpan = 1;
    privateKeyAdd.setLayoutData(gd);

    ssh2HomeBrowse.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            String home = ssh2HomeText.getText();

            if (!new File(home).exists()) {
                while (true) {
                    int foo = home.lastIndexOf(java.io.File.separator, home.length());
                    if (foo == -1)
                        break;
                    home = home.substring(0, foo);
                    if (new File(home).exists())
                        break;
                }
            }

            DirectoryDialog dd = new DirectoryDialog(getShell());
            dd.setFilterPath(home);
            dd.setMessage(Messages.CVSSSH2PreferencePage_27);
            String dir = dd.open();
            if (dir == null) { // cancel
                return;
            }
            ssh2HomeText.setText(dir);
        }
    });

    privateKeyAdd.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            String home = ssh2HomeText.getText();

            FileDialog fd = new FileDialog(getShell(), SWT.OPEN | SWT.MULTI);
            fd.setFilterPath(home);
            Object o = fd.open();
            if (o == null) { // cancel
                return;
            }
            String[] files = fd.getFileNames();
            String keys = privateKeyText.getText();
            String dir = fd.getFilterPath();
            if (dir.equals(home)) {
                dir = ""; //$NON-NLS-1$
            } else {
                dir += java.io.File.separator;
            }

            for (int i = 0; i < files.length; i++) {
                String foo = files[i];
                if (keys.length() != 0)
                    keys = keys + ","; //$NON-NLS-1$
                keys = keys + dir + foo;
            }
            privateKeyText.setText(keys);
        }
    });

    return group;
}

From source file:org.eclipse.jsch.internal.ui.preference.PreferencePage.java

License:Open Source License

private Control createKeyManagementPage(Composite parent) {
    int columnSpan = 3;
    Composite group = new Composite(parent, SWT.NULL);
    GridLayout layout = new GridLayout();
    layout.numColumns = 3;//from ww w. j  a v a2s  .co m
    layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
    layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
    group.setLayout(layout);
    GridData gd = new GridData();
    gd.horizontalAlignment = GridData.FILL;
    group.setLayoutData(gd);

    keyGenerateDSA = new Button(group, SWT.NULL);
    keyGenerateDSA.setText(Messages.CVSSSH2PreferencePage_131);
    gd = new GridData();
    gd.horizontalSpan = 1;
    keyGenerateDSA.setLayoutData(gd);

    keyGenerateRSA = new Button(group, SWT.NULL);
    keyGenerateRSA.setText(Messages.CVSSSH2PreferencePage_132);
    gd = new GridData();
    gd.horizontalSpan = 1;
    keyGenerateRSA.setLayoutData(gd);

    keyLoad = new Button(group, SWT.NULL);
    keyLoad.setText(Messages.CVSSSH2PreferencePage_128);
    gd = new GridData();
    gd.horizontalSpan = 1;
    keyLoad.setLayoutData(gd);

    publicKeylabel = new Label(group, SWT.NONE);
    publicKeylabel.setText(Messages.CVSSSH2PreferencePage_39);
    gd = new GridData();
    gd.horizontalSpan = columnSpan;
    publicKeylabel.setLayoutData(gd);

    publicKeyText = new Text(group, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.WRAP | SWT.LEFT_TO_RIGHT);
    publicKeyText.setText(""); //$NON-NLS-1$
    publicKeyText.setEditable(false);
    gd = new GridData();
    gd.horizontalSpan = columnSpan;
    gd.horizontalAlignment = GridData.FILL;
    gd.verticalAlignment = GridData.FILL;
    gd.grabExcessHorizontalSpace = true;
    gd.grabExcessVerticalSpace = true;
    publicKeyText.setLayoutData(gd);

    keyFingerPrintLabel = new Label(group, SWT.NONE);
    keyFingerPrintLabel.setText(Messages.CVSSSH2PreferencePage_41);
    keyFingerPrintText = new Text(group, SWT.SINGLE | SWT.BORDER | SWT.LEFT_TO_RIGHT);
    keyFingerPrintText.setFont(group.getFont());
    keyFingerPrintText.setEditable(false);
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    keyFingerPrintText.setLayoutData(gd);

    keyCommentLabel = new Label(group, SWT.NONE);
    keyCommentLabel.setText(Messages.CVSSSH2PreferencePage_42);
    keyCommentText = new Text(group, SWT.SINGLE | SWT.BORDER);
    keyCommentText.setFont(group.getFont());
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    keyCommentText.setLayoutData(gd);

    keyCommentText.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            if (kpair == null)
                return;
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                kpairComment = keyCommentText.getText();
                kpair.writePublicKey(out, kpairComment);
                out.close();
                publicKeyText.setText(out.toString());
            } catch (IOException ee) {
                // Ignore
            }
        }
    });

    keyPassphrase1Label = new Label(group, SWT.NONE);
    keyPassphrase1Label.setText(Messages.CVSSSH2PreferencePage_43);
    keyPassphrase1Text = new Text(group, SWT.SINGLE | SWT.BORDER);
    keyPassphrase1Text.setFont(group.getFont());
    keyPassphrase1Text.setEchoChar('*');
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    keyPassphrase1Text.setLayoutData(gd);

    keyPassphrase2Label = new Label(group, SWT.NONE);
    keyPassphrase2Label.setText(Messages.CVSSSH2PreferencePage_44);
    keyPassphrase2Text = new Text(group, SWT.SINGLE | SWT.BORDER);
    keyPassphrase2Text.setFont(group.getFont());
    keyPassphrase2Text.setEchoChar('*');
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    keyPassphrase2Text.setLayoutData(gd);

    keyPassphrase1Text.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            String pass1 = keyPassphrase1Text.getText();
            String pass2 = keyPassphrase2Text.getText();
            if (kpair != null && pass1.equals(pass2)) {
                saveKeyPair.setEnabled(true);
            } else {
                saveKeyPair.setEnabled(false);
            }
            if (pass2.length() == 0) {
                setErrorMessage(null);
                return;
            }
            if (pass1.equals(pass2)) {
                setErrorMessage(null);
            } else {
                setErrorMessage(Messages.CVSSSH2PreferencePage_48);
            }
        }
    });

    keyPassphrase2Text.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            String pass1 = keyPassphrase1Text.getText();
            String pass2 = keyPassphrase2Text.getText();
            if (kpair != null && pass1.equals(pass2)) {
                saveKeyPair.setEnabled(true);
            } else {
                saveKeyPair.setEnabled(false);
            }
            if (pass2.length() < pass1.length()) {
                if (pass1.startsWith(pass2)) {
                    setErrorMessage(null);
                } else {
                    setErrorMessage(Messages.CVSSSH2PreferencePage_48);
                }
                return;
            }
            if (pass1.equals(pass2)) {
                setErrorMessage(null);
            } else {
                setErrorMessage(Messages.CVSSSH2PreferencePage_48);
            }
        }
    });

    keyPassphrase2Text.addFocusListener(new FocusListener() {
        public void focusGained(FocusEvent e) {
            String pass1 = keyPassphrase1Text.getText();
            String pass2 = keyPassphrase2Text.getText();
            if (pass2.length() < pass1.length()) {
                if (pass1.startsWith(pass2)) {
                    setErrorMessage(null);
                } else {
                    setErrorMessage(Messages.CVSSSH2PreferencePage_48);
                }
                return;
            }
            if (pass1.equals(pass2)) {
                setErrorMessage(null);
            } else {
                setErrorMessage(Messages.CVSSSH2PreferencePage_48);
            }
        }

        public void focusLost(FocusEvent e) {
            String pass1 = keyPassphrase1Text.getText();
            String pass2 = keyPassphrase2Text.getText();
            if (pass1.equals(pass2)) {
                setErrorMessage(null);
            } else {
                setErrorMessage(Messages.CVSSSH2PreferencePage_48);
            }
        }
    });

    Composite buttons = new Composite(group, SWT.NONE);
    layout = new GridLayout(2, true);
    layout.marginWidth = 0;
    layout.marginHeight = 0;
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
    buttons.setLayout(layout);
    gd = new GridData(GridData.HORIZONTAL_ALIGN_END);
    gd.horizontalSpan = columnSpan;
    buttons.setLayoutData(gd);

    keyExport = new Button(buttons, SWT.NULL);
    keyExport.setText(Messages.CVSSSH2PreferencePage_105);
    gd = new GridData(GridData.FILL_BOTH);
    keyExport.setLayoutData(gd);

    saveKeyPair = new Button(buttons, SWT.NULL);
    saveKeyPair.setText(Messages.CVSSSH2PreferencePage_45);
    gd = new GridData(GridData.FILL_BOTH);
    saveKeyPair.setLayoutData(gd);

    SelectionAdapter keygenadapter = new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            boolean ok = true;
            String _type = ""; //$NON-NLS-1$

            try {
                int type = 0;
                if (e.widget == keyGenerateDSA) {
                    type = KeyPair.DSA;
                    _type = IConstants.DSA;
                } else if (e.widget == keyGenerateRSA) {
                    type = KeyPair.RSA;
                    _type = IConstants.RSA;
                } else {
                    return;
                }

                final KeyPair[] _kpair = new KeyPair[1];
                final int __type = type;
                final JSchException[] _e = new JSchException[1];
                BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
                    public void run() {
                        try {
                            _kpair[0] = KeyPair.genKeyPair(getJSch(), __type);
                        } catch (JSchException e) {
                            _e[0] = e;
                        }
                    }
                });
                if (_e[0] != null) {
                    throw _e[0];
                }
                kpair = _kpair[0];

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                kpairComment = _type + "-1024"; //$NON-NLS-1$
                kpair.writePublicKey(out, kpairComment);
                out.close();
                publicKeyText.setText(out.toString());
                keyFingerPrintText.setText(kpair.getFingerPrint());
                keyCommentText.setText(kpairComment);
                keyPassphrase1Text.setText(""); //$NON-NLS-1$
                keyPassphrase2Text.setText(""); //$NON-NLS-1$
                updateControls();
            } catch (IOException ee) {
                ok = false;
            } catch (JSchException ee) {
                ok = false;
            }
            if (!ok) {
                MessageDialog.openError(getShell(), Messages.CVSSSH2PreferencePage_error,
                        Messages.CVSSSH2PreferencePage_47);
            }
        }
    };
    keyGenerateDSA.addSelectionListener(keygenadapter);
    keyGenerateRSA.addSelectionListener(keygenadapter);

    keyLoad.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            boolean ok = true;
            String home = ssh2HomeText.getText();
            FileDialog fd = new FileDialog(getShell(), SWT.OPEN);
            fd.setFilterPath(home);
            Object o = fd.open();
            if (o == null) { // cancel
                return;
            }
            String pkey = fd.getFileName();
            String pkeyab = (new File(fd.getFilterPath(), pkey)).getAbsolutePath();
            try {
                KeyPair _kpair = KeyPair.load(getJSch(), pkeyab);
                PassphrasePrompt prompt = null;
                while (_kpair.isEncrypted()) {
                    if (prompt == null) {
                        prompt = new PassphrasePrompt(
                                NLS.bind(Messages.CVSSSH2PreferencePage_126, new String[] { pkey }));
                    }
                    Display.getDefault().syncExec(prompt);
                    String passphrase = prompt.getPassphrase();
                    if (passphrase == null)
                        break;
                    if (_kpair.decrypt(passphrase)) {
                        break;
                    }
                    MessageDialog.openError(getShell(), Messages.CVSSSH2PreferencePage_error,
                            NLS.bind(Messages.CVSSSH2PreferencePage_129, new String[] { pkey }));
                }
                if (_kpair.isEncrypted()) {
                    return;
                }
                kpair = _kpair;
                String _type = (kpair.getKeyType() == KeyPair.DSA) ? IConstants.DSA : IConstants.RSA;
                kpairComment = _type + "-1024"; //$NON-NLS-1$

                // TODO Bug 351094 The comment should be from kpair object,
                // but the JSch API does not provided such a method.
                // In the version 0.1.45, JSch will support such a method,
                // and the following code should be replaced with it at that time.
                java.io.FileInputStream fis = null;
                try {
                    java.io.File f = new java.io.File(pkeyab + ".pub"); //$NON-NLS-1$
                    int i = 0;
                    fis = new java.io.FileInputStream(f);
                    byte[] buf = new byte[(int) f.length()];
                    while (i < buf.length) {
                        int j = fis.read(buf, i, buf.length - i);
                        if (j <= 0)
                            break;
                        i += j;
                    }
                    String pubkey = new String(buf);
                    if (pubkey.indexOf(' ') > 0 && pubkey.indexOf(' ', pubkey.indexOf(' ') + 1) > 0) {
                        int j = pubkey.indexOf(' ', pubkey.indexOf(' ') + 1) + 1;
                        kpairComment = pubkey.substring(j);
                        if (kpairComment.indexOf('\n') > 0) {
                            kpairComment = kpairComment.substring(0, kpairComment.indexOf('\n'));
                        }
                    }
                } catch (IOException ioe) {
                    // ignore if public-key does not exist.
                } finally {
                    if (fis != null)
                        fis.close();
                }

                ByteArrayOutputStream out = new ByteArrayOutputStream();

                kpair.writePublicKey(out, kpairComment);
                out.close();
                publicKeyText.setText(out.toString());
                keyFingerPrintText.setText(kpair.getFingerPrint());
                keyCommentText.setText(kpairComment);
                keyPassphrase1Text.setText(""); //$NON-NLS-1$
                keyPassphrase2Text.setText(""); //$NON-NLS-1$
                updateControls();
            } catch (IOException ee) {
                ok = false;
            } catch (JSchException ee) {
                ok = false;
            }
            if (!ok) {
                MessageDialog.openError(getShell(), Messages.CVSSSH2PreferencePage_error,
                        Messages.CVSSSH2PreferencePage_130);
            }
        }
    });

    keyExport.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            if (kpair == null)
                return;

            setErrorMessage(null);

            final String[] target = new String[1];
            final String title = Messages.CVSSSH2PreferencePage_106;
            final String message = Messages.CVSSSH2PreferencePage_107;
            Display.getDefault().syncExec(new Runnable() {
                public void run() {
                    Display display = Display.getCurrent();
                    Shell shell = new Shell(display);
                    ExportDialog dialog = new ExportDialog(shell, title, message);
                    dialog.open();
                    shell.dispose();
                    target[0] = dialog.getTarget();
                }
            });
            if (target[0] == null) {
                return;
            }
            String user = ""; //$NON-NLS-1$
            String host = ""; //$NON-NLS-1$
            int port = 22;

            if (target[0].indexOf('@') > 0) {
                user = target[0].substring(0, target[0].indexOf('@'));
                host = target[0].substring(target[0].indexOf('@') + 1);
            }
            if (host.indexOf(':') > 0) {
                try {
                    port = Integer.parseInt(host.substring(host.indexOf(':') + 1));
                } catch (NumberFormatException ee) {
                    port = -1;
                }
                host = host.substring(0, host.indexOf(':'));
            }

            if (user.length() == 0 || host.length() == 0 || port == -1) {
                setErrorMessage(NLS.bind(Messages.CVSSSH2PreferencePage_108, new String[] { target[0] }));
                return;
            }

            String options = ""; //$NON-NLS-1$
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                if (options.length() != 0) {
                    try {
                        bos.write((options + " ").getBytes()); //$NON-NLS-1$
                    } catch (IOException eeee) {
                        // Ignore
                    }
                }
                kpair.writePublicKey(bos, kpairComment);
                bos.close();
                export_via_sftp(user, host, port, /* ".ssh/authorized_keys", //$NON-NLS-1$ */
                        bos.toByteArray());
            } catch (IOException ee) {
                // Ignore
            } catch (JSchException ee) {
                setErrorMessage(Messages.CVSSSH2PreferencePage_111);
            }
        }
    });

    saveKeyPair.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            if (kpair == null)
                return;

            String pass = keyPassphrase1Text.getText();
            /*
             * if(!pass.equals(keyPassphrase2Text.getText())){
             * setErrorMessage(Policy.bind("CVSSSH2PreferencePage.48"));
             * //$NON-NLS-1$ return; }
             */
            if (pass.length() == 0) {
                if (!MessageDialog.openConfirm(getShell(), Messages.CVSSSH2PreferencePage_confirmation,
                        Messages.CVSSSH2PreferencePage_49)) {
                    return;
                }
            }

            kpair.setPassphrase(pass);

            String home = ssh2HomeText.getText();

            File _home = new File(home);

            if (!_home.exists()) {
                if (!MessageDialog.openConfirm(getShell(), Messages.CVSSSH2PreferencePage_confirmation,
                        NLS.bind(Messages.CVSSSH2PreferencePage_50, new String[] { home }))) {
                    return;
                }
                if (!_home.mkdirs()) {
                    setErrorMessage(Messages.CVSSSH2PreferencePage_100 + home);
                    return;
                }
            }

            FileDialog fd = new FileDialog(getShell(), SWT.SAVE);
            fd.setFilterPath(home);
            String file = (kpair.getKeyType() == KeyPair.RSA) ? "id_rsa" : "id_dsa"; //$NON-NLS-1$ //$NON-NLS-2$
            fd.setFileName(file);
            file = fd.open();
            if (file == null) { // cancel
                return;
            }

            if (new File(file).exists()) {
                if (!MessageDialog.openConfirm(getShell(), Messages.CVSSSH2PreferencePage_confirmation, // 
                        NLS.bind(Messages.CVSSSH2PreferencePage_53, new String[] { file }))) {
                    return;
                }
            }

            boolean ok = true;
            try {
                kpair.writePrivateKey(file);
                kpair.writePublicKey(file + ".pub", kpairComment); //$NON-NLS-1$
            } catch (Exception ee) {
                ok = false;
            }

            if (ok) {
                MessageDialog.openInformation(getShell(), Messages.CVSSSH2PreferencePage_information,
                        Messages.CVSSSH2PreferencePage_55 + "\n" + //$NON-NLS-1$
                Messages.CVSSSH2PreferencePage_57 + file + "\n" + //$NON-NLS-1$
                Messages.CVSSSH2PreferencePage_59 + file + ".pub"); //$NON-NLS-1$
            } else {
                return;
            }

            // The generated key should be added to privateKeyText.

            String dir = fd.getFilterPath();
            File mypkey = new java.io.File(dir, fd.getFileName());
            String pkeys = privateKeyText.getText();

            // Check if the generated key has been included in pkeys?
            String[] pkeysa = pkeys.split(","); //$NON-NLS-1$
            for (int i = 0; i < pkeysa.length; i++) {
                File pkey = new java.io.File(pkeysa[i]);
                if (!pkey.isAbsolute()) {
                    pkey = new java.io.File(home, pkeysa[i]);
                }
                if (pkey.equals(mypkey))
                    return;
            }

            if (dir.equals(home)) {
                dir = ""; //$NON-NLS-1$
            } else {
                dir += java.io.File.separator;
            }
            if (pkeys.length() > 0)
                pkeys += ","; //$NON-NLS-1$
            pkeys = pkeys + dir + fd.getFileName();
            privateKeyText.setText(pkeys);
        }
    });

    return group;
}