Example usage for org.eclipse.jface.viewers TreeViewer getSelection

List of usage examples for org.eclipse.jface.viewers TreeViewer getSelection

Introduction

In this page you can find the example usage for org.eclipse.jface.viewers TreeViewer getSelection.

Prototype

@Override
public ISelection getSelection() 

Source Link

Document

The AbstractTreeViewer implementation of this method returns the result as an ITreeSelection.

Usage

From source file:com.isencia.passerelle.workbench.model.editor.ui.views.ActorTreeMenuProvider.java

License:Open Source License

/**
 * Builds the context menu. Single selection menu and multiple selection menu are created while selecting just single
 * element or multiple elements/*w  w  w  . j  a  v  a  2 s . c  o  m*/
 * 
 * 
 * @param menu
 *          the menu
 */
public void buildContextMenu(IMenuManager menu) {

    menu.add(new Separator(GEFActionConstants.GROUP_EDIT));

    // IAction action = getActionRegistry().getAction(
    // ActionFactory.DELETE.getId());
    // if (action != null && action.isEnabled())
    TreeViewer tree = (TreeViewer) getViewer();
    TreeSelection treeSelection = (TreeSelection) tree.getSelection();
    Object element = treeSelection.getFirstElement();
    if (element instanceof SubModelPaletteItemDefinition) {
        createCompositeMenu(menu, element);
    } else if (element instanceof PaletteGroup) {
        if (((PaletteGroup) element).getId().equals("com.isencia.passerelle.actor.actorgroup.submodels")) {
            createCompositeMenu(menu, element);
        }
    }

}

From source file:com.iw.plugins.spindle.html.HTMLContentOutlinePage.java

License:Mozilla Public License

private void fillContextMenu(IMenuManager manager) {
    TreeViewer viewer = (TreeViewer) getTreeViewer();
    IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();

    IFile file = Utils.findRelatedComponent(documentFile);

    IStructuredSelection canCreateSelection = filterSelection(file, selection);

    if (canCreateSelection.isEmpty() && selection.size() == 1) {

        ILabelProvider provider = (ILabelProvider) getTreeViewer().getLabelProvider();

        openAction.configure(file, provider.getText(selection.getFirstElement()));
        manager.add(openAction);/*from w  w  w  .  j a va  2s  .c o  m*/

    } else {

        createAction.configure(file, canCreateSelection);
        manager.add(createAction);
    }

}

From source file:com.mindquarry.desktop.preferences.dialog.FilteredPreferenceDialog.java

License:Open Source License

/**
 * Add the listeners to the tree viewer.
 * //from   ww w. ja  v  a 2 s .co m
 * @param viewer
 * 
 * @since 3.1
 */
protected void addListeners(final TreeViewer viewer) {
    viewer.addPostSelectionChangedListener(new ISelectionChangedListener() {
        private void handleError() {
            try {
                // remove the listener temporarily so that the events caused
                // by the error handling dont further cause error handling
                // to occur.
                viewer.removePostSelectionChangedListener(this);
                showPageFlippingAbortDialog();
                selectCurrentPageAgain();
                clearSelectedNode();
            } finally {
                viewer.addPostSelectionChangedListener(this);
            }
        }

        public void selectionChanged(SelectionChangedEvent event) {
            Object selection = getSingleSelection(event.getSelection());
            if (selection instanceof IPreferenceNode) {
                if (!isCurrentPageValid()) {
                    handleError();
                } else if (!showPage((IPreferenceNode) selection)) {
                    // Page flipping wasn't successful
                    handleError();
                } else {
                    // Everything went well
                    lastSuccessfulNode = (IPreferenceNode) selection;
                }
            }
        }
    });
    ((Tree) viewer.getControl()).addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetDefaultSelected(final SelectionEvent event) {
            ISelection selection = viewer.getSelection();
            if (selection.isEmpty()) {
                return;
            }
            IPreferenceNode singleSelection = getSingleSelection(selection);
            boolean expanded = viewer.getExpandedState(singleSelection);
            viewer.setExpandedState(singleSelection, !expanded);
        }
    });
    // Register help listener on the tree to use context sensitive help
    viewer.getControl().addHelpListener(new HelpListener() {
        public void helpRequested(HelpEvent event) {
            // call perform help on the current page
            if (currentPage != null) {
                currentPage.performHelp();
            }
        }
    });
}

From source file:com.nokia.carbide.cpp.internal.project.ui.views.SymbianProjectNavigatorView.java

License:Open Source License

public void setWorkingSet(IWorkingSet workingSet) {
    TreeViewer treeViewer = getViewer();
    Object[] expanded = treeViewer.getExpandedElements();
    ISelection selection = treeViewer.getSelection();

    workingSetFilter.setWorkingSet(workingSet);

    treeViewer.refresh();/*w  w  w.j  a  v a2s  .co m*/
    treeViewer.setExpandedElements(expanded);
    if (selection.isEmpty() == false && selection instanceof IStructuredSelection) {
        IStructuredSelection structuredSelection = (IStructuredSelection) selection;
        treeViewer.reveal(structuredSelection.getFirstElement());
    }
}

From source file:com.safi.workshop.sqlexplorer.plugin.views.DatabaseStructureView.java

License:Open Source License

/**
 * Add a new session to the database structure view. This will create a new tab for the
 * session./*from ww w . jav  a2 s .co m*/
 * 
 * @param session
 */
private void addSession(final MetaDataSession session) throws SQLCannotConnectException {
    if (_allSessions.contains(session))
        return;
    try {
        session.getMetaData();
        session.setAutoCommit(true);
    } catch (SQLCannotConnectException e) {
        SQLExplorerPlugin.error(e);
        throw e;
    } catch (SQLException e) {
        SQLExplorerPlugin.error(e);
        MessageDialog.openError(getSite().getShell(), "Cannot connect", e.getMessage());
    }
    DatabaseNode rootNode = session.getRoot();
    if (rootNode == null)
        return;
    _allSessions.add(session);

    if (_filterAction != null) {
        _filterAction.setEnabled(true);
    }

    if (_tabFolder == null || _tabFolder.isDisposed()) {

        clearParent();

        // create tab folder for different sessions
        _tabFolder = new CTabFolder(_parent, SWT.TOP | SWT.CLOSE);

        // add listener to keep both views on the same active tab
        _tabFolder.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                // set the selected node in the detail view.
                DatabaseDetailView detailView = (DatabaseDetailView) getSite().getPage()
                        .findView(SqlexplorerViewConstants.SQLEXPLORER_DBDETAIL);
                synchronizeDetailView(detailView);
            }

        });

        // Set up a gradient background for the selected tab
        Display display = getSite().getShell().getDisplay();
        _tabFolder.setSelectionBackground(
                new Color[] { display.getSystemColor(SWT.COLOR_WHITE), new Color(null, 211, 225, 250),
                        new Color(null, 175, 201, 246), IConstants.TAB_BORDER_COLOR },
                new int[] { 25, 50, 75 }, true);

        // Add a listener to handle the close button on each tab
        _tabFolder.addCTabFolder2Listener(new CTabFolder2Adapter() {
            @Override
            public void close(CTabFolderEvent event) {
                CTabItem tabItem = (CTabItem) event.item;
                TabData tabData = (TabData) tabItem.getData();
                _allSessions.remove(tabData.session);
                event.doit = true;
            }
        });

        _parent.layout();
        _parent.redraw();

    }

    // create tab
    final CTabItem tabItem = new CTabItem(_tabFolder, SWT.NULL);
    TabData tabData = new TabData();
    tabItem.setData(tabData);
    tabData.session = session;

    // set tab text
    String labelText = session.getUser().getDescription();
    tabItem.setText(labelText);

    // create composite for our outline
    Composite composite = new Composite(_tabFolder, SWT.NULL);
    composite.setLayout(new FillLayout());
    tabItem.setControl(composite);

    // create outline
    final TreeViewer treeViewer = new TreeViewer(composite,
            SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER);
    tabData.treeViewer = treeViewer;

    // add drag support
    // TODO improve drag support options
    Transfer[] transfers = new Transfer[] { TableNodeTransfer.getInstance() };
    treeViewer.addDragSupport(DND.DROP_COPY, transfers, new DragSourceListener() {

        public void dragFinished(DragSourceEvent event) {

            System.out.println("$drag finished");
            TableNodeTransfer.getInstance().setSelection(null);
        }

        public void dragSetData(DragSourceEvent event) {

            Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            event.data = sel;
        }

        public void dragStart(DragSourceEvent event) {

            event.doit = !treeViewer.getSelection().isEmpty();
            if (event.doit) {
                Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
                if (!(sel instanceof TableNode)) {
                    event.doit = false;
                } else {
                    TableNode tn = (TableNode) sel;
                    TableNodeTransfer.getInstance().setSelection(tn);
                    if (!tn.isTable())
                        event.doit = false;
                }
            }
        }
    });

    // use hash lookup to improve performance
    treeViewer.setUseHashlookup(true);

    // add content and label provider
    treeViewer.setContentProvider(new DBTreeContentProvider());
    treeViewer.setLabelProvider(new DBTreeLabelProvider());

    // set input session
    treeViewer.setInput(rootNode);

    // add selection change listener, so we can update detail view as
    // required.
    treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent ev) {

            // set the selected node in the detail view.
            DatabaseDetailView detailView = (DatabaseDetailView) getSite().getPage()
                    .findView(SqlexplorerViewConstants.SQLEXPLORER_DBDETAIL);
            synchronizeDetailView(detailView);
        }
    });

    // bring detail to front on doubleclick of node
    treeViewer.addDoubleClickListener(new IDoubleClickListener() {

        public void doubleClick(DoubleClickEvent event) {

            try {
                // find view
                DatabaseDetailView detailView = (DatabaseDetailView) getSite().getPage()
                        .findView(SqlexplorerViewConstants.SQLEXPLORER_DBDETAIL);
                if (detailView == null) {
                    getSite().getPage().showView(SqlexplorerViewConstants.SQLEXPLORER_DBDETAIL);
                }
                getSite().getPage().bringToTop(detailView);
                synchronizeDetailView(detailView);
            } catch (Exception e) {
                // fail silent
            }
        }

    });

    // add expand/collapse listener
    treeViewer.addTreeListener(new ITreeViewerListener() {

        public void treeCollapsed(TreeExpansionEvent event) {

            // refresh the node to change image
            INode node = (INode) event.getElement();
            node.setExpanded(false);
            TreeViewer viewer = (TreeViewer) event.getSource();
            viewer.update(node, null);
        }

        public void treeExpanded(TreeExpansionEvent event) {

            // refresh the node to change image
            INode node = (INode) event.getElement();
            node.setExpanded(true);
            TreeViewer viewer = (TreeViewer) event.getSource();
            viewer.update(node, null);
        }

    });

    // set new tab as the active one
    _tabFolder.setSelection(_tabFolder.getItemCount() - 1);

    // update detail view
    DatabaseDetailView detailView = (DatabaseDetailView) getSite().getPage()
            .findView(SqlexplorerViewConstants.SQLEXPLORER_DBDETAIL);

    if (detailView != null) {

        // synchronze detail view with new session
        synchronizeDetailView(detailView);

        // bring detail to top of the view stack
        getSite().getPage().bringToTop(detailView);
    }

    // refresh view
    composite.layout();
    _tabFolder.layout();
    _tabFolder.redraw();

    // bring this view to top of the view stack, above detail if needed..
    getSite().getPage().bringToTop(this);

    // add context menu
    final DBTreeActionGroup actionGroup = new DBTreeActionGroup(treeViewer);
    MenuManager menuManager = new MenuManager("DBTreeContextMenu");
    menuManager.setRemoveAllWhenShown(true);
    Menu contextMenu = menuManager.createContextMenu(treeViewer.getTree());
    treeViewer.getTree().setMenu(contextMenu);

    menuManager.addMenuListener(new IMenuListener() {

        public void menuAboutToShow(IMenuManager manager) {

            actionGroup.fillContextMenu(manager);
        }
    });
}

From source file:de.rowlo.diffeclipse.controller.DiffEclipseFormController.java

License:Open Source License

protected void enableButtonExtractMissingExtensions() {
    TreeViewer treeViewer = getForm().getTreeViewerMissingExtensions();
    ISelection selection = treeViewer.getSelection();
    boolean enabled = !selection.isEmpty();

    Button button = getForm().getButtonExtractMissingExtensions();
    button.setEnabled(enabled);/*from www.jav  a  2s .c  om*/
}

From source file:de.walware.ecommons.ui.util.ViewerUtil.java

License:Open Source License

public static void scheduleStandardSelection(final TreeViewer viewer) {
    viewer.getControl().getDisplay().asyncExec(new Runnable() {
        @Override/*from  w  w  w. j  a v a  2 s. com*/
        public void run() {
            final ISelection selection = viewer.getSelection();
            if (selection.isEmpty()) {
                if (viewer.getTree().getItemCount() > 0) {
                    final TreeItem item = viewer.getTree().getItem(0);
                    viewer.setSelection(new TreeSelection(new TreePath(new Object[] { item.getData() })));
                    viewer.setExpandedState(item.getData(), true);
                } else {
                    viewer.setSelection(new StructuredSelection());
                }
            }
        }
    });
}

From source file:edu.washington.cs.cupid.wizards.ui.MappingPage.java

License:Open Source License

/**
 * Returns the capability selected from the capability listing; returns <tt>null</tt>
 * if no element is selected.//from   w  w w. j  av  a2s .c  o m
 * @param viewer the capability viewer
 * @return the capability selected from the capability listing, or <tt>null</tt> if no element is selected
 */
private ISerializableCapability selectedCapability(TreeViewer viewer) {
    Object selected = ((IStructuredSelection) viewer.getSelection()).getFirstElement();

    if (selected == null) {
        return null;
    } else if (selected instanceof ISerializableCapability) {
        return (ISerializableCapability) selected;
    } else if (selected instanceof ICapability) {
        return new DynamicSerializablePipeline(null, null,
                Lists.<Serializable>newArrayList(((ICapability) selected).getName()),
                Lists.<ICapabilityArguments>newArrayList(CapabilityArguments.NONE));
    } else if (selected instanceof DerivedCapability) {
        return ((DerivedCapability) selected).toPipeline();
    } else {
        throw new RuntimeException("Unexpected tree entry");
    }
}

From source file:es.cv.gvcase.emf.ui.common.dialogs.FeatureEditorDialog.java

License:Open Source License

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

    GridLayout contentsGridLayout = (GridLayout) contents.getLayout();
    contentsGridLayout.numColumns = 3;//from   ww  w .  j  a  v  a 2s . c  o  m

    GridData contentsGridData = (GridData) contents.getLayoutData();
    contentsGridData.horizontalAlignment = SWT.FILL;
    contentsGridData.verticalAlignment = SWT.FILL;

    Text patternText = null;

    if (choiceOfValues != null) {
        Group filterGroupComposite = new Group(contents, SWT.NONE);
        filterGroupComposite.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Choices_pattern_group"));
        filterGroupComposite.setLayout(new GridLayout(2, false));
        filterGroupComposite.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false, 3, 1));

        Label label = new Label(filterGroupComposite, SWT.NONE);
        label.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Choices_pattern_label"));

        patternText = new Text(filterGroupComposite, SWT.BORDER);
        patternText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    }

    Composite choiceComposite = new Composite(contents, SWT.NONE);
    {
        GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
        data.horizontalAlignment = SWT.END;
        choiceComposite.setLayoutData(data);

        GridLayout layout = new GridLayout();
        data.horizontalAlignment = SWT.FILL;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.numColumns = 1;
        choiceComposite.setLayout(layout);
    }

    Label choiceLabel = new Label(choiceComposite, SWT.NONE);
    choiceLabel.setText(choiceOfValues == null ? EMFEditUIPlugin.INSTANCE.getString("_UI_Value_label")
            : EMFEditUIPlugin.INSTANCE.getString("_UI_Choices_label"));
    GridData choiceLabelGridData = new GridData();
    choiceLabelGridData.verticalAlignment = SWT.FILL;
    choiceLabelGridData.horizontalAlignment = SWT.FILL;
    choiceLabel.setLayoutData(choiceLabelGridData);

    final Tree choiceTree = choiceOfValues == null ? null : new Tree(choiceComposite, SWT.MULTI | SWT.BORDER);
    if (choiceTree != null) {
        GridData choiceTtreeGridData = new GridData();
        choiceTtreeGridData.widthHint = Display.getCurrent().getBounds().width / 5;
        choiceTtreeGridData.heightHint = Display.getCurrent().getBounds().height / 3;
        choiceTtreeGridData.verticalAlignment = SWT.FILL;
        choiceTtreeGridData.horizontalAlignment = SWT.FILL;
        choiceTtreeGridData.grabExcessHorizontalSpace = true;
        choiceTtreeGridData.grabExcessVerticalSpace = true;
        choiceTree.setLayoutData(choiceTtreeGridData);
    }

    final TreeViewer choiceTreeViewer = choiceOfValues == null ? null : new TreeViewer(choiceTree);
    if (choiceTreeViewer != null) {
        choiceTreeViewer.setContentProvider(contentProvider);
        choiceTreeViewer.setLabelProvider(labelProvider);
        final PatternFilter filter = new PatternFilter() {
            @Override
            protected boolean isParentMatch(Viewer viewer, Object element) {
                return viewer instanceof AbstractTreeViewer && super.isParentMatch(viewer, element);
            }
        };
        choiceTreeViewer.addFilter(filter);
        assert patternText != null;
        patternText.addModifyListener(new ModifyListener() {
            public void modifyText(ModifyEvent e) {
                filter.setPattern(((Text) e.widget).getText());
                choiceTreeViewer.refresh();
            }
        });
        choiceTreeViewer.setInput(choiceOfValues);

        choiceTreeViewer.expandToLevel(2);
    }

    // We use multi even for a single line because we want to respond to the
    // enter key.
    //
    int style = multiLine ? SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER : SWT.MULTI | SWT.BORDER;
    final Text choiceText = choiceOfValues == null ? new Text(choiceComposite, style) : null;
    if (choiceText != null) {
        GridData choiceTextGridData = new GridData();
        choiceTextGridData.widthHint = Display.getCurrent().getBounds().width / 5;
        choiceTextGridData.verticalAlignment = SWT.BEGINNING;
        choiceTextGridData.horizontalAlignment = SWT.FILL;
        choiceTextGridData.grabExcessHorizontalSpace = true;
        if (multiLine) {
            choiceTextGridData.verticalAlignment = SWT.FILL;
            choiceTextGridData.grabExcessVerticalSpace = true;
        }
        choiceText.setLayoutData(choiceTextGridData);
    }

    Composite controlButtons = new Composite(contents, SWT.NONE);
    GridData controlButtonsGridData = new GridData();
    controlButtonsGridData.verticalAlignment = SWT.FILL;
    controlButtonsGridData.horizontalAlignment = SWT.FILL;
    controlButtons.setLayoutData(controlButtonsGridData);

    GridLayout controlsButtonGridLayout = new GridLayout();
    controlButtons.setLayout(controlsButtonGridLayout);

    new Label(controlButtons, SWT.NONE);

    final Button addButton = new Button(controlButtons, SWT.PUSH);
    addButton.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Add_label"));
    GridData addButtonGridData = new GridData();
    addButtonGridData.verticalAlignment = SWT.FILL;
    addButtonGridData.horizontalAlignment = SWT.FILL;
    addButton.setLayoutData(addButtonGridData);

    final Button removeButton = new Button(controlButtons, SWT.PUSH);
    removeButton.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Remove_label"));
    GridData removeButtonGridData = new GridData();
    removeButtonGridData.verticalAlignment = SWT.FILL;
    removeButtonGridData.horizontalAlignment = SWT.FILL;
    removeButton.setLayoutData(removeButtonGridData);

    Label spaceLabel = new Label(controlButtons, SWT.NONE);
    GridData spaceLabelGridData = new GridData();
    spaceLabelGridData.verticalSpan = 2;
    spaceLabel.setLayoutData(spaceLabelGridData);

    final Button upButton = new Button(controlButtons, SWT.PUSH);
    upButton.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Up_label"));
    GridData upButtonGridData = new GridData();
    upButtonGridData.verticalAlignment = SWT.FILL;
    upButtonGridData.horizontalAlignment = SWT.FILL;
    upButton.setLayoutData(upButtonGridData);

    final Button downButton = new Button(controlButtons, SWT.PUSH);
    downButton.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Down_label"));
    GridData downButtonGridData = new GridData();
    downButtonGridData.verticalAlignment = SWT.FILL;
    downButtonGridData.horizontalAlignment = SWT.FILL;
    downButton.setLayoutData(downButtonGridData);

    Composite featureComposite = new Composite(contents, SWT.NONE);
    {
        GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
        data.horizontalAlignment = SWT.END;
        featureComposite.setLayoutData(data);

        GridLayout layout = new GridLayout();
        data.horizontalAlignment = SWT.FILL;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.numColumns = 1;
        featureComposite.setLayout(layout);
    }

    Label featureLabel = new Label(featureComposite, SWT.NONE);
    featureLabel.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Feature_label"));
    GridData featureLabelGridData = new GridData();
    featureLabelGridData.horizontalSpan = 2;
    featureLabelGridData.horizontalAlignment = SWT.FILL;
    featureLabelGridData.verticalAlignment = SWT.FILL;
    featureLabel.setLayoutData(featureLabelGridData);

    final Tree featureTree = new Tree(featureComposite, SWT.MULTI | SWT.BORDER);
    GridData featureTreeGridData = new GridData();
    featureTreeGridData.widthHint = Display.getCurrent().getBounds().width / 5;
    featureTreeGridData.heightHint = Display.getCurrent().getBounds().height / 3;
    featureTreeGridData.verticalAlignment = SWT.FILL;
    featureTreeGridData.horizontalAlignment = SWT.FILL;
    featureTreeGridData.grabExcessHorizontalSpace = true;
    featureTreeGridData.grabExcessVerticalSpace = true;
    featureTree.setLayoutData(featureTreeGridData);

    final TreeViewer featureTreeViewer = new TreeViewer(featureTree);
    featureTreeViewer.setContentProvider(contentProvider);
    featureTreeViewer.setLabelProvider(labelProvider);
    if (values != null) {
        featureTreeViewer.setInput(values);
        if (!values.getChildren().isEmpty()) {
            featureTreeViewer.setSelection(new StructuredSelection(values.getChildren().get(0)));
        }
    } else {
        featureTreeViewer.setInput(currentValues);
        if (!currentValues.isEmpty()) {
            featureTreeViewer.setSelection(new StructuredSelection(currentValues.get(0)));
        }
    }
    featureTreeViewer.expandToLevel(2);

    if (choiceTreeViewer != null) {
        choiceTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
            public void doubleClick(DoubleClickEvent event) {
                if (addButton.isEnabled()) {
                    addButton.notifyListeners(SWT.Selection, null);
                }
            }
        });

        featureTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
            public void doubleClick(DoubleClickEvent event) {
                if (removeButton.isEnabled()) {
                    removeButton.notifyListeners(SWT.Selection, null);
                }
            }
        });
    }

    if (choiceText != null) {
        choiceText.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent event) {
                if (!multiLine && (event.character == '\r' || event.character == '\n')) {
                    try {
                        Object value = EcoreUtil.createFromString((EDataType) eClassifier,
                                choiceText.getText());
                        if (values != null) {
                            values.getChildren().add(value);
                        } else {
                            currentValues.add(value);
                        }
                        choiceText.setText("");
                        featureTreeViewer.setSelection(new StructuredSelection(value));
                        event.doit = false;
                    } catch (RuntimeException exception) {
                        // Ignore
                    }
                } else if (event.character == '\33') {
                    choiceText.setText("");
                    event.doit = false;
                }
            }
        });
    }

    upButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            IStructuredSelection selection = (IStructuredSelection) featureTreeViewer.getSelection();
            int minIndex = 0;
            for (Iterator<?> i = selection.iterator(); i.hasNext();) {
                Object value = i.next();
                if (values != null) {
                    int index = values.getChildren().indexOf(value);
                    values.getChildren().move(Math.max(index - 1, minIndex++), value);
                } else {
                    int index = currentValues.indexOf(value);
                    currentValues.remove(value);
                    currentValues.add(Math.max(index - 1, minIndex++), value);
                }
            }
            featureTreeViewer.refresh();
            featureTreeViewer.expandToLevel(2);
            featureTreeViewer.setSelection(selection);
        }
    });

    downButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            IStructuredSelection selection = (IStructuredSelection) featureTreeViewer.getSelection();
            int maxIndex = 0;
            if (values != null) {
                maxIndex = values.getChildren().size();
            } else {
                maxIndex = currentValues.size();
            }
            maxIndex = maxIndex - selection.size();
            for (Iterator<?> i = selection.iterator(); i.hasNext();) {
                Object value = i.next();
                if (values != null) {
                    int index = values.getChildren().indexOf(value);
                    values.getChildren().move(Math.min(index + 1, maxIndex++), value);
                } else {
                    int index = currentValues.indexOf(value);
                    currentValues.remove(value);
                    currentValues.add(Math.min(index + 1, maxIndex++), value);
                }
            }
            featureTreeViewer.refresh();
            featureTreeViewer.expandToLevel(2);
            featureTreeViewer.setSelection(selection);
        }
    });

    addButton.addSelectionListener(new SelectionAdapter() {
        // event is null when choiceTableViewer is double clicked
        @Override
        public void widgetSelected(SelectionEvent event) {
            if (choiceTreeViewer != null) {
                IStructuredSelection selection = (IStructuredSelection) choiceTreeViewer.getSelection();
                for (Iterator<?> i = selection.iterator(); i.hasNext();) {
                    Object value = i.next();
                    if (!eClassifier.isInstance(value)) {
                        continue;
                    }
                    if (values != null) {
                        if (!values.getChildren().contains(value)) {
                            values.getChildren().add(value);
                        }
                    } else {
                        if (!currentValues.contains(value)) {
                            currentValues.add(value);
                        }
                    }
                }
                featureTreeViewer.refresh();
                featureTreeViewer.expandToLevel(2);
                featureTreeViewer.setSelection(selection);
            } else if (choiceText != null) {
                try {
                    Object value = EcoreUtil.createFromString((EDataType) eClassifier, choiceText.getText());
                    if (values != null) {
                        values.getChildren().add(value);
                    } else {
                        currentValues.add(value);
                    }
                    choiceText.setText("");
                    featureTreeViewer.refresh(value);
                    featureTreeViewer.setSelection(new StructuredSelection(value));
                } catch (RuntimeException exception) {
                    // Ignore
                }
            }
        }
    });

    removeButton.addSelectionListener(new SelectionAdapter() {
        // event is null when featureTableViewer is double clicked
        @Override
        public void widgetSelected(SelectionEvent event) {
            IStructuredSelection selection = (IStructuredSelection) featureTreeViewer.getSelection();
            Object firstValue = null;
            for (Iterator<?> i = selection.iterator(); i.hasNext();) {
                Object value = i.next();
                if (!eClassifier.isInstance(value)) {
                    continue;
                }
                if (firstValue == null) {
                    firstValue = value;
                }
                if (values != null) {
                    values.getChildren().remove(value);
                } else {
                    currentValues.remove(value);
                }
            }

            if (values != null) {
                if (!values.getChildren().isEmpty()) {
                    featureTreeViewer.setSelection(new StructuredSelection(values.getChildren().get(0)));
                }
            } else {
                if (!currentValues.isEmpty()) {
                    featureTreeViewer.setSelection(new StructuredSelection(currentValues.get(0)));
                }
            }

            if (choiceTreeViewer != null) {
                choiceTreeViewer.refresh();
                choiceTreeViewer.expandToLevel(2);
                featureTreeViewer.refresh();
                featureTreeViewer.expandToLevel(2);
                choiceTreeViewer.setSelection(selection);
            } else if (choiceText != null) {
                if (firstValue != null) {
                    String value = EcoreUtil.convertToString((EDataType) eClassifier, firstValue);
                    choiceText.setText(value);
                }
            }
        }
    });

    return contents;
}

From source file:es.cv.gvcase.fefem.common.composites.EMFContainedHierarchicalCollectionEditionComposite.java

License:Open Source License

/**
 * Creates the a SelectionListener which will invoke the code to remove/delete
 * a selected element from the tree viewer.
 *     /*from   ww w . j a  v  a2  s. com*/
 * @return SelectionListener the {@link SelectionListener} which will
 * remove/delete a selected element from the viewer.  
 */
protected SelectionListener getRemoveButtonSelectionListener() {
    SelectionAdapter adapter = new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {

            TreeViewer viewer = getViewer();
            if (viewer.getSelection() instanceof TreeSelection) {
                TreeSelection selection = (TreeSelection) viewer.getSelection();
                List<?> elementsToDelete = selection.toList();
                if (elementsToDelete.size() > 0) {
                    // We prepare the next selection, based on the element to delete
                    EObject eObject = (EObject) elementsToDelete.get(0);
                    TreePath path = selection.getPathsFor(eObject)[0];
                    TreeSelection nextSelection = TreeSelection.EMPTY;
                    ;
                    if (path.getSegmentCount() == 1) { // If it is a first level element, we will select a sibling element
                        if (modelObservable.size() > 1) { // If we have more than one element 
                            int pos = modelObservable.indexOf(eObject);
                            nextSelection = (pos == modelObservable.size() - 1) // If it's the last first level element, we will select the previous sibling
                                    ? new TreeSelection(
                                            new TreePath(new Object[] { modelObservable.get(pos - 1) }))
                                    : new TreeSelection(
                                            new TreePath(new Object[] { modelObservable.get(pos + 1) })); // otherwise, we will select the next one
                        }
                    } else { // If it is not a first level element, we will select its parent element
                        nextSelection = new TreeSelection(path.getParentPath());
                    }

                    EditingDomain domain = getEditingDomain();
                    domain.getCommandStack().execute(DeleteCommand.create(domain, elementsToDelete));
                    getPage().setDirty(true);
                    viewer.setSelection(nextSelection);
                }
            }
        }
    };
    return adapter;
}