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.aptana.explorer.internal.ui.FilteringProjectView.java

License:Open Source License

/**
 * Update the in-memory memento for a given project. This update method should be called before saving the memento
 * and before every project switch.//  w  ww  . ja va 2  s .co m
 * 
 * @param project
 */
protected void updateProjectMementoCache(IProject project) {
    TreeViewer viewer = getCommonViewer();
    if (viewer == null || project == null) {
        return;
    }
    List<String> expanded = new ArrayList<String>();
    List<String> selected = new ArrayList<String>();

    // Save the expansion state
    Object expandedElements[] = viewer.getVisibleExpandedElements();
    if (expandedElements.length > 0) {
        for (int i = 0; i < expandedElements.length; i++) {
            if (expandedElements[i] instanceof IResource) {
                expanded.add(((IResource) expandedElements[i]).getFullPath().toString());
            }
        }
    }
    // Save the selection state
    Object selectedElements[] = ((IStructuredSelection) viewer.getSelection()).toArray();
    if (selectedElements.length > 0) {
        for (int i = 0; i < selectedElements.length; i++) {
            if (selectedElements[i] instanceof IResource) {
                selected.add(((IResource) selectedElements[i]).getFullPath().toString());
            }
        }
    }
    projectExpansions.put(project, expanded);
    projectSelections.put(project, selected);

    // FIXME Need to store filters in a way that we can store the filename search filter too!
    IResource filter = getFilterResource();
    if (filter != null) {
        projectFilters.put(project, filter.getLocation().toPortableString());
    } else {
        projectFilters.remove(project);
    }
}

From source file:com.aptana.ide.editors.views.profiles.ProfilesView.java

License:Open Source License

/**
 * createTreeViewer/*w  w w . j av a  2 s.c  o m*/
 * 
 * @param parent
 * @return TreeViewer
 */
protected TreeViewer createTreeViewer(Composite parent) {
    final TreeViewer treeViewer = new TreeViewer(new Tree(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL));
    GridData tvData = new GridData(SWT.FILL, SWT.FILL, true, true);
    treeViewer.getTree().setLayoutData(tvData);
    treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent event) {
            Object[] paths = ((ITreeSelection) treeViewer.getSelection()).toArray();
            actionMakeCurrent.setEnabled(paths.length == 1 && paths[0] instanceof Profile);
            for (int i = 0; i < paths.length; i++) {
                if (paths[i] instanceof Profile) {
                    actionMoveDown.setEnabled(false);
                    actionMoveUp.setEnabled(false);
                    return;
                }
            }
            actionMoveDown.setEnabled(true);
            actionMoveUp.setEnabled(true);
        }

    });

    // Implement a "fake" tooltip
    final Listener labelListener = new Listener() {
        public void handleEvent(Event event) {
            StyledText label = (StyledText) event.widget;
            Shell shell = (Shell) label.getData("_SHELL"); //$NON-NLS-1$
            switch (event.type) {
            case SWT.MouseDown:
                Event e = new Event();
                e.item = (TreeItem) label.getData("_TREEITEM"); //$NON-NLS-1$
                // Assuming table is single select, set the selection as if
                // the mouse down event went through to the table
                treeViewer.getTree().setSelection(new TreeItem[] { (TreeItem) e.item });
                treeViewer.getTree().notifyListeners(SWT.Selection, e);
                // fall through
            case SWT.MouseExit:
                shell.dispose();
                break;
            default:
                break;
            }
        }
    };

    final Shell shell = getSite().getShell();

    Listener tableListener = new Listener() {
        UnifiedInformationControl info = null;

        public void handleEvent(Event event) {
            switch (event.type) {
            case SWT.Dispose:
            case SWT.KeyDown:
            case SWT.MouseMove: {
                if (info == null || info.getShell() == null) {
                    break;
                }
                info.getShell().dispose();
                info = null;
                break;
            }
            case SWT.MouseHover: {
                TreeItem item = treeViewer.getTree().getItem(new Point(event.x, event.y));
                if (item != null) {
                    if (info != null && info.getShell() != null && !info.getShell().isDisposed()) {
                        info.getShell().dispose();
                    }

                    info = new UnifiedInformationControl(shell, SWT.NONE, new HTMLTextPresenter(false));

                    info.getStyledTextWidget().setData("_TREEITEM", item); //$NON-NLS-1$
                    info.getStyledTextWidget().setData("_SHELL", info.getShell()); //$NON-NLS-1$
                    info.getStyledTextWidget().addListener(SWT.MouseExit, labelListener);
                    info.getStyledTextWidget().addListener(SWT.MouseDown, labelListener);

                    Object data = item.getData();
                    String txt = null;

                    if (data instanceof Profile) {
                        Profile profile = (Profile) data;
                        txt = StringUtils.format(Messages.ProfilesView_ProfileItems,
                                new Object[] { profile.getName(), Integer.toString(profile.getURIs().length) });
                    } else if (data instanceof ProfileURI) {
                        ProfileURI uri = (ProfileURI) data;
                        txt = StringUtils.urlDecodeFilename(uri.getURI().toCharArray());
                    }

                    if (txt != null) {
                        info.setSizeConstraints(300, 500);
                        info.setInformation(txt);

                        StyledText styledText = info.getStyledTextWidget();
                        GC gc = new GC(styledText);
                        int width = gc.getFontMetrics().getAverageCharWidth();

                        width = ((txt.length() + 2) * width);

                        Rectangle rect = item.getBounds(0);
                        Point pt = treeViewer.getTree().toDisplay(20 + rect.x, rect.y);

                        info.setSize(width, 0);
                        info.setLocation(pt);
                        info.setVisible(true);
                    }
                }
            }
            default:
                break;
            }
        }
    };

    treeViewer.getTree().addListener(SWT.Dispose, tableListener);
    treeViewer.getTree().addListener(SWT.KeyDown, tableListener);
    treeViewer.getTree().addListener(SWT.MouseMove, tableListener);
    treeViewer.getTree().addListener(SWT.MouseHover, tableListener);

    return treeViewer;
}

From source file:com.aptana.ide.syncing.ui.old.views.SmartSyncViewer.java

License:Open Source License

private TreeViewer createContents(final Composite parent) {
    final TreeViewer viewer = new TreeViewer(parent, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
    viewer.setContentProvider(fContentProvider = new SmartSyncContentProvider());
    viewer.setLabelProvider(fLabelProvider = new SmartSyncLabelProvider(parent.getDisplay()));

    Tree tree = viewer.getTree();/*from  w  w w. j ava  2  s  . c  o  m*/
    tree.setLinesVisible(true);
    tree.setHeaderVisible(true);
    viewer.setAutoExpandLevel(2);
    tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    fInitBackground = new Color(tree.getDisplay(), 175, 238, 238);
    fProgressBackground = new Color(tree.getDisplay(), 72, 209, 204);
    tree.addDisposeListener(new DisposeListener() {

        public void widgetDisposed(DisposeEvent e) {
            fInitBackground.dispose();
            fProgressBackground.dispose();
        }

    });
    parent.addControlListener(new ControlAdapter() {

        public void controlResized(ControlEvent e) {
            setWidth(parent.getSize().x);
        }

    });

    // file column
    TreeColumn file = new TreeColumn(tree, SWT.LEFT);
    file.setWidth(250);
    file.setText(Messages.SmartSyncDialog_ColumnResources);
    file.setToolTipText(Messages.SmartSyncViewer_ColumnResourcesTooltip);

    // the column to specify whether the file should be skipped
    TreeColumn skip = new TreeColumn(tree, SWT.CENTER);
    skip.setWidth(40);
    skip.setText(Messages.SmartSyncDialog_ColumnSkip);
    skip.setToolTipText(Messages.SmartSyncViewer_ColumnSkipTooltip);

    // the state column on what will be done, if any, to the files from first end point
    fColumnEnd1 = new TreeColumn(tree, SWT.CENTER);
    fColumnEnd1.setWidth(125);

    // the state column on what will be done, if any, to the files from second end point
    fColumnEnd2 = new TreeColumn(tree, SWT.CENTER);
    fColumnEnd2.setWidth(125);

    Menu menu = new Menu(tree);
    fShowDiffs = new MenuItem(menu, SWT.PUSH);
    fShowDiffs.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent e) {
            if (!viewer.getSelection().isEmpty() && viewer.getSelection() instanceof IStructuredSelection) {
                Object selection = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
                if (selection instanceof SyncFile) {
                    SyncFile file = (SyncFile) selection;
                    if (file.getSyncState() == SyncState.ClientItemIsNewer
                            || file.getSyncState() == SyncState.ServerItemIsNewer) {
                        final VirtualFileSyncPair pair = file.getPair();
                        FileStoreCompareEditorInput input = new FileStoreCompareEditorInput(
                                new CompareConfiguration());
                        input.setLeftFileStore(pair.getSourceFile());
                        IFileStore destinationFile = pair.getDestinationFile();
                        String name = destinationFile.getName();
                        if (destinationFile instanceof IExtendedFileStore) {
                            // this is a remote file, so downloads to a local temp copy first for speed purpose
                            try {
                                File localFile = destinationFile.toLocalFile(EFS.CACHE, null);
                                destinationFile = EFS.getLocalFileSystem()
                                        .getStore(Path.fromOSString(localFile.getAbsolutePath()));
                            } catch (CoreException ce) {
                                // logs as warning since we will fall back to use the remote file store directly in
                                // this case
                                IdeLog.logWarning(SyncingUIPlugin.getDefault(), ce);
                            }
                        }
                        input.setRightFileStore(destinationFile, name);
                        input.initializeCompareConfiguration();
                        CompareUI.openCompareDialog(input);
                    }
                }
            }
        }
    });
    fShowDiffs.setImage(SyncingUIPlugin.getImage("icons/full/obj16/compare_view.gif")); //$NON-NLS-1$
    fShowDiffs.setText(Messages.SmartSyncDialog_ShowDiffs);
    fShowDiffs.setEnabled(true);
    tree.setMenu(menu);

    viewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent event) {
            if (!viewer.getSelection().isEmpty() && viewer.getSelection() instanceof IStructuredSelection) {
                Object selection = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
                if (selection instanceof SyncFile) {
                    SyncFile file = (SyncFile) selection;
                    if (file.getSyncState() == SyncState.ClientItemIsNewer
                            || file.getSyncState() == SyncState.ServerItemIsNewer) {
                        fShowDiffs.setEnabled(true);
                        return;
                    }
                }
            }
            fShowDiffs.setEnabled(false);
        }

    });
    viewer.setCellEditors(new CellEditor[] { null, new CheckboxCellEditor(), null, null });
    viewer.setColumnProperties(
            new String[] { Messages.SmartSyncDialog_ColumnName, Messages.SmartSyncDialog_ColumnSkip,
                    Messages.SmartSyncDialog_ColumnLocal, Messages.SmartSyncDialog_ColumnRemote });

    return viewer;
}

From source file:com.aptana.ide.syncing.ui.views.SmartSyncViewer.java

License:Open Source License

private TreeViewer createContents(final Composite parent) {
    final TreeViewer viewer = new TreeViewer(parent, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
    viewer.setContentProvider(fContentProvider = new SmartSyncContentProvider());
    viewer.setLabelProvider(fLabelProvider = new SmartSyncLabelProvider(parent.getDisplay()));

    Tree tree = viewer.getTree();//from w  w w  .  ja  v a2 s  . co  m
    tree.setLinesVisible(true);
    tree.setHeaderVisible(true);
    viewer.setAutoExpandLevel(2);
    tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    fInitBackground = new Color(tree.getDisplay(), 175, 238, 238);
    fProgressBackground = new Color(tree.getDisplay(), 72, 209, 204);
    tree.addDisposeListener(new DisposeListener() {

        public void widgetDisposed(DisposeEvent e) {
            fInitBackground.dispose();
            fProgressBackground.dispose();
        }

    });
    parent.addControlListener(new ControlAdapter() {

        public void controlResized(ControlEvent e) {
            setWidth(parent.getSize().x);
        }

    });

    // file column
    TreeColumn file = new TreeColumn(tree, SWT.LEFT);
    file.setWidth(250);
    file.setText(Messages.SmartSyncDialog_ColumnResources);
    file.setToolTipText(Messages.SmartSyncViewer_ColumnResourcesTooltip);

    // the column to specify whether the file should be skipped
    TreeColumn skip = new TreeColumn(tree, SWT.CENTER);
    skip.setWidth(40);
    skip.setText(Messages.SmartSyncDialog_ColumnSkip);
    skip.setToolTipText(Messages.SmartSyncViewer_ColumnSkipTooltip);

    // the state column on what will be done, if any, to the files from first end point
    fColumnEnd1 = new TreeColumn(tree, SWT.CENTER);
    fColumnEnd1.setWidth(125);

    // the state column on what will be done, if any, to the files from second end point
    fColumnEnd2 = new TreeColumn(tree, SWT.CENTER);
    fColumnEnd2.setWidth(125);

    Menu menu = new Menu(tree);
    fShowDiffs = new MenuItem(menu, SWT.PUSH);
    fShowDiffs.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent e) {
            if (!viewer.getSelection().isEmpty() && viewer.getSelection() instanceof IStructuredSelection) {
                Object selection = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
                if (selection instanceof SyncFile) {
                    SyncFile file = (SyncFile) selection;
                    if (file.getSyncState() == SyncState.ClientItemIsNewer
                            || file.getSyncState() == SyncState.ServerItemIsNewer) {
                        final VirtualFileSyncPair pair = file.getPair();
                        File local = null;
                        try {
                            local = pair.getSourceFile().toLocalFile(EFS.CACHE, null);
                        } catch (CoreException ex) {
                            ex.printStackTrace();
                        }

                        FileCompareEditorInput input = new FileCompareEditorInput(new CompareConfiguration()) {
                            protected void prepareFiles() {
                                File temp = null;
                                try {
                                    temp = pair.getDestinationFile().toLocalFile(EFS.CACHE, null);
                                } catch (CoreException e) {
                                    e.printStackTrace();
                                }
                                setRightResource(temp);
                            }
                        };
                        input.setLeftResource(local);
                        CompareUI.openCompareDialog(input);
                    }
                }
            }
        }

    });
    fShowDiffs.setImage(SyncingUIPlugin.getImage("icons/full/obj16/compare_view.gif")); //$NON-NLS-1$
    fShowDiffs.setText(Messages.SmartSyncDialog_ShowDiffs);
    fShowDiffs.setEnabled(true);
    tree.setMenu(menu);

    viewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent event) {
            if (!viewer.getSelection().isEmpty() && viewer.getSelection() instanceof IStructuredSelection) {
                Object selection = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
                if (selection instanceof SyncFile) {
                    SyncFile file = (SyncFile) selection;
                    if (file.getSyncState() == SyncState.ClientItemIsNewer
                            || file.getSyncState() == SyncState.ServerItemIsNewer) {
                        fShowDiffs.setEnabled(true);
                        return;
                    }
                }
            }
            fShowDiffs.setEnabled(false);
        }

    });
    viewer.setCellEditors(new CellEditor[] { null, new CheckboxCellEditor(), null, null });
    viewer.setColumnProperties(
            new String[] { Messages.SmartSyncDialog_ColumnName, Messages.SmartSyncDialog_ColumnSkip,
                    Messages.SmartSyncDialog_ColumnLocal, Messages.SmartSyncDialog_ColumnRemote });

    return viewer;
}

From source file:com.atlassian.connector.eclipse.internal.crucible.ui.wizards.SelectChangesetsFromCruciblePage.java

License:Open Source License

private TreeSelection getTreeSelection(TreeViewer treeViewer) {
    ISelection selection = treeViewer.getSelection();
    if (selection instanceof TreeSelection) {
        return (TreeSelection) selection;
    }//from   www . j av  a2  s.c  o m
    return null;
}

From source file:com.buildml.eclipse.utils.dialogs.VFSTreeSelectionDialog.java

License:Open Source License

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

    /* customize the dialog box, before it's opened */
    final TreeViewer viewer = getTreeViewer();
    viewer.expandToLevel(5);/*from  w w w .  j ava2s  .c o  m*/

    /* 
     * Unless the user is allowed to select directories, disable the OK button if
     * a directory is selected.
     */
    if (!allowDirs) {
        viewer.addSelectionChangedListener(new ISelectionChangedListener() {
            @Override
            public void selectionChanged(SelectionChangedEvent event) {
                ITreeSelection selection = (ITreeSelection) viewer.getSelection();
                Object element = selection.getFirstElement();
                getButton(OK).setEnabled(!(element instanceof UIDirectory));
            }
        });
    }

    return contents;
}

From source file:com.clustercontrol.monitor.view.action.EventFilterAction.java

License:Open Source License

/**
 * [??]?????????//from  w  ww  .ja v  a2  s  .com
 * ???
 * <p>
 * <ol>
 * <li>[??]???</li>
 * <li>????????</li>
 * <li>[]??????</li>
 * <li>[]???</li>
 * </ol>
 *
 * @see org.eclipse.core.commands.IHandler#execute
 * @see com.clustercontrol.monitor.dialog.EventFilterDialog
 * @see com.clustercontrol.monitor.view.EventView#setCondition(Property)
 * @see com.clustercontrol.monitor.view.EventView#update()
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    this.window = HandlerUtil.getActiveWorkbenchWindow(event);
    // ???
    this.viewPart = HandlerUtil.getActivePart(event);

    EventView view = null;
    try {
        view = (EventView) this.viewPart.getAdapter(EventView.class);
    } catch (Exception e) {
        m_log.info("execute " + e.getMessage());
        return null;
    }

    if (view == null) {
        m_log.info("execute: view is null");
        return null;
    }

    ICommandService commandService = (ICommandService) window.getService(ICommandService.class);
    Command command = commandService.getCommand(ID);
    boolean isChecked = !HandlerUtil.toggleCommandState(command);

    if (isChecked) {
        // ?
        EventFilterDialog dialog = new EventFilterDialog(this.viewPart.getSite().getShell());

        // ??????????
        if (dialog.open() == IDialogConstants.OK_ID) {

            Property condition = dialog.getInputData();

            view.setCondition(condition);
            view.update(false);
        } else {
            State state = command.getState(RegistryToggleState.STATE_ID);
            state.setValue(false);
        }
    } else {
        // ?
        view.setCondition(null);
        // ???(?????)
        TreeViewer tree = view.getScopeTreeComposite().getTreeViewer();

        // ????????
        if (((StructuredSelection) tree.getSelection()).getFirstElement() != null) {
            tree.setSelection(tree.getSelection()); // ??
        }
        // ?????????
        else {
            view.update(false);
        }
    }
    return null;
}

From source file:com.clustercontrol.monitor.view.action.StatusFilterAction.java

License:Open Source License

/**
 * [??]?????????/*w ww .  ja  v a  2  s.co  m*/
 * ???
 * <p>
 * <ol>
 * <li>[??]???</li>
 * <li>????????</li>
 * <li>[]??????</li>
 * <li>[]???</li>
 * </ol>
 *
 * @see org.eclipse.core.commands.IHandler#execute
 * @see com.clustercontrol.monitor.dialog.StatusFilterDialog
 * @see com.clustercontrol.monitor.view.StatusView#setCondition(Property)
 * @see com.clustercontrol.monitor.view.StatusView#update()
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    this.window = HandlerUtil.getActiveWorkbenchWindow(event);
    // In case this action has been disposed
    if (null == this.window || !isEnabled()) {
        return null;
    }

    // ???
    this.viewPart = HandlerUtil.getActivePart(event);
    StatusView statusView = null;
    try {
        statusView = (StatusView) this.viewPart.getAdapter(StatusView.class);
    } catch (Exception e) {
        m_log.info("execute " + e.getMessage());
        return null;
    }

    if (statusView == null) {
        m_log.info("execute: view is null");
        return null;
    }

    ICommandService commandService = (ICommandService) window.getService(ICommandService.class);
    Command command = commandService.getCommand(ID);
    boolean isChecked = !HandlerUtil.toggleCommandState(command);

    if (isChecked) {
        // ?
        StatusFilterDialog dialog = new StatusFilterDialog(this.viewPart.getSite().getShell());

        // ??????????
        if (dialog.open() == IDialogConstants.OK_ID) {
            Property condition = dialog.getInputData();

            statusView.setCondition(condition);
            statusView.update(false);
        } else {
            State state = command.getState(RegistryToggleState.STATE_ID);
            state.setValue(false);
        }
    } else {
        // ?
        statusView.setCondition(null);

        // ???(?????)
        TreeViewer tree = statusView.getScopeTreeComposite().getTreeViewer();

        // ????????
        if (((StructuredSelection) tree.getSelection()).getFirstElement() != null) {
            tree.setSelection(tree.getSelection()); // ??
        }
        // ?????????
        else {
            statusView.update(false);
        }
    }
    return null;
}

From source file:com.google.devtools.depan.eclipse.ui.nodes.viewers.GraphNodeViewer.java

License:Apache License

private void setupHierarchyMenu(final TreeViewer viewer) {
    MenuManager menuMgr = new MenuManager();

    Menu menu = menuMgr.createContextMenu(viewer.getControl());

    menuMgr.addMenuListener(new IMenuListener() {

        @Override/*ww w  .  jav a  2 s  . c  om*/
        public void menuAboutToShow(IMenuManager manager) {
            ISelection selection = viewer.getSelection();
            List<?> choices = Selections.getObjects(selection);
            if (choices.isEmpty()) {
                return;
            }
            if (choices.size() > 1) {
                addMultiActions(manager);
                return;
            }

            Object menuElement = Selections.getFirstObject(selection);
            addItemActions(manager, menuElement);
        }
    });

    menuMgr.setRemoveAllWhenShown(true);
    viewer.getControl().setMenu(menu);
}

From source file:com.hydra.project.myplugin_nebula.xviewer.customize.dialog.XViewerCustomizeDialog.java

License:Open Source License

private List<XViewerColumn> getTableSelection(TreeViewer xColTableViewer) {
    List<XViewerColumn> xCols = new ArrayList<XViewerColumn>();
    IStructuredSelection selection = (IStructuredSelection) xColTableViewer.getSelection();
    if (selection.isEmpty()) {
        return null;
    }/*from  w w w . ja v  a 2s.  co m*/
    Iterator<?> i = selection.iterator();
    while (i.hasNext()) {
        xCols.add((XViewerColumn) i.next());
    }
    return xCols;
}