Example usage for org.eclipse.jface.viewers IStructuredSelection toList

List of usage examples for org.eclipse.jface.viewers IStructuredSelection toList

Introduction

In this page you can find the example usage for org.eclipse.jface.viewers IStructuredSelection toList.

Prototype

public List toList();

Source Link

Document

Returns the elements in this selection as a List.

Usage

From source file:com.android.ide.eclipse.auidt.internal.wizards.newxmlfile.NewXmlFileCreationPage.java

License:Open Source License

/**
 * Called by {@link NewXmlFileWizard} to initialize the page with the selection
 * received by the wizard -- typically the current user workbench selection.
 * <p/>/*w w w.  j av a2s  . com*/
 * Things we expect to find out from the selection:
 * <ul>
 * <li>The project name, valid if it's an android nature.</li>
 * <li>The current folder, valid if it's a folder under /res</li>
 * <li>An existing filename, in which case the user will be asked whether to override it.</li>
 * </ul>
 * <p/>
 * The selection can also be set to a {@link Pair} of {@link IProject} and a workspace
 * resource path (where the resource path does not have to exist yet, such as res/anim/).
 *
 * @param selection The selection when the wizard was initiated.
 */
private boolean initializeFromSelection(IStructuredSelection selection) {
    if (selection == null) {
        return false;
    }

    // Find the best match in the element list. In case there are multiple selected elements
    // select the one that provides the most information and assign them a score,
    // e.g. project=1 + folder=2 + file=4.
    IProject targetProject = null;
    String targetWsFolderPath = null;
    String targetFileName = null;
    int targetScore = 0;
    for (Object element : selection.toList()) {
        if (element instanceof IAdaptable) {
            IResource res = (IResource) ((IAdaptable) element).getAdapter(IResource.class);
            IProject project = res != null ? res.getProject() : null;

            // Is this an Android project?
            try {
                if (project == null || !project.hasNature(AdtConstants.NATURE_DEFAULT)) {
                    continue;
                }
            } catch (CoreException e) {
                // checking the nature failed, ignore this resource
                continue;
            }

            int score = 1; // we have a valid project at least

            IPath wsFolderPath = null;
            String fileName = null;
            assert res != null; // Eclipse incorrectly thinks res could be null, so tell it no
            if (res.getType() == IResource.FOLDER) {
                wsFolderPath = res.getProjectRelativePath();
            } else if (res.getType() == IResource.FILE) {
                if (AdtUtils.endsWithIgnoreCase(res.getName(), DOT_XML)) {
                    fileName = res.getName();
                }
                wsFolderPath = res.getParent().getProjectRelativePath();
            }

            // Disregard this folder selection if it doesn't point to /res/something
            if (wsFolderPath != null && wsFolderPath.segmentCount() > 1
                    && SdkConstants.FD_RESOURCES.equals(wsFolderPath.segment(0))) {
                score += 2;
            } else {
                wsFolderPath = null;
                fileName = null;
            }

            score += fileName != null ? 4 : 0;

            if (score > targetScore) {
                targetScore = score;
                targetProject = project;
                targetWsFolderPath = wsFolderPath != null ? wsFolderPath.toString() : null;
                targetFileName = fileName;
            }
        } else if (element instanceof Pair<?, ?>) {
            // Pair of Project/String
            @SuppressWarnings("unchecked")
            Pair<IProject, String> pair = (Pair<IProject, String>) element;
            targetScore = 1;
            targetProject = pair.getFirst();
            targetWsFolderPath = pair.getSecond();
            targetFileName = "";
        }
    }

    if (targetProject == null) {
        // Try to figure out the project from the active editor
        IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        if (window != null) {
            IWorkbenchPage page = window.getActivePage();
            if (page != null) {
                IEditorPart activeEditor = page.getActiveEditor();
                if (activeEditor instanceof AndroidXmlEditor) {
                    Object input = ((AndroidXmlEditor) activeEditor).getEditorInput();
                    if (input instanceof FileEditorInput) {
                        FileEditorInput fileInput = (FileEditorInput) input;
                        targetScore = 1;
                        IFile file = fileInput.getFile();
                        targetProject = file.getProject();
                        IPath path = file.getParent().getProjectRelativePath();
                        targetWsFolderPath = path != null ? path.toString() : null;
                    }
                }
            }
        }
    }

    if (targetProject == null) {
        // If we didn't find a default project based on the selection, check how many
        // open Android projects we can find in the current workspace. If there's only
        // one, we'll just select it by default.
        IJavaProject[] projects = AdtUtils.getOpenAndroidProjects();
        if (projects != null && projects.length == 1) {
            targetScore = 1;
            targetProject = projects[0].getProject();
        }
    }

    // Now set the UI accordingly
    if (targetScore > 0) {
        mValues.project = targetProject;
        mValues.folderPath = targetWsFolderPath;
        mProjectButton.setSelectedProject(targetProject);
        mFileNameTextField.setText(targetFileName != null ? targetFileName : ""); //$NON-NLS-1$

        // If the current selection context corresponds to a specific file type,
        // select it.
        if (targetWsFolderPath != null) {
            int pos = targetWsFolderPath.lastIndexOf(WS_SEP_CHAR);
            if (pos >= 0) {
                targetWsFolderPath = targetWsFolderPath.substring(pos + 1);
            }
            String[] folderSegments = targetWsFolderPath.split(RES_QUALIFIER_SEP);
            if (folderSegments.length > 0) {
                String folderName = folderSegments[0];
                selectTypeFromFolder(folderName);
            }
        }
    }

    return true;
}

From source file:com.android.ide.eclipse.gltrace.views.detail.DetailsPage.java

License:Apache License

private IGLProperty getSelectedProperty(StateView view, ISelection selection) {
    if (!(selection instanceof IStructuredSelection)) {
        return null;
    }/*from  www . j ava  2  s  .c  o m*/

    IStructuredSelection ssel = (IStructuredSelection) selection;
    @SuppressWarnings("rawtypes")
    List objects = ssel.toList();
    if (objects.size() > 0) {
        Object data = objects.get(0);
        if (data instanceof IGLProperty) {
            return (IGLProperty) data;
        }
    }

    return null;
}

From source file:com.android.ide.eclipse.gltrace.views.GLFramebufferView.java

License:Apache License

public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    if (!(part instanceof GLFunctionTraceViewer)) {
        return;/*from  w  w  w. j  a v  a  2s . com*/
    }

    if (!(selection instanceof IStructuredSelection)) {
        return;
    }

    IStructuredSelection ssel = (IStructuredSelection) selection;
    @SuppressWarnings("rawtypes")
    List objects = ssel.toList();
    if (objects.size() > 0) {
        Object data = objects.get(0);
        if (data instanceof GLCall) {
            GLCall glCall = (GLCall) data;
            if (!glCall.hasFb()) {
                return;
            }

            GLFunctionTraceViewer traceViewer = (GLFunctionTraceViewer) part;
            GLTrace glTrace = traceViewer.getTrace();
            displayFB(glTrace.getImage(glCall));
        }
    }
}

From source file:com.android.ide.eclipse.gltrace.views.GLStateView.java

License:Apache License

public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    if (!(part instanceof GLFunctionTraceViewer)) {
        return;//from w w w.j a  v a  2 s  .  c o m
    }

    if (!(selection instanceof IStructuredSelection)) {
        return;
    }

    GLFunctionTraceViewer traceViewer = (GLFunctionTraceViewer) part;
    GLCall selectedCall = null;

    IStructuredSelection ssel = (IStructuredSelection) selection;
    if (ssel.toList().size() > 0) {
        Object data = ssel.toList().get(0);
        if (data instanceof GLCall) {
            selectedCall = (GLCall) data;
        }
    }

    GLTrace trace = traceViewer.getTrace();
    if (trace == null) {
        return;
    }

    if (selectedCall != mCurrentGLCall) {
        IGLProperty nextState = trace.getStateAt(selectedCall);
        if (nextState != mState) {
            mState = nextState;
            mStateChanged = true;
        } else {
            mStateChanged = false;
        }

        mChangedProperties = trace.getChangedProperties(mCurrentGLCall, selectedCall, mState);

        refreshUI();
        mCurrentGLCall = selectedCall;
    }
}

From source file:com.aptana.git.ui.internal.actions.AbstractGitHandler.java

License:Open Source License

protected Collection<IResource> getSelectedResources() {
    if (selectedResources != null) {
        return selectedResources;
    }/*from w w  w  .j a va2 s.co m*/

    Collection<IResource> resources = new ArrayList<IResource>();
    Object activePart = evalContext.getVariable(ISources.ACTIVE_PART_NAME);
    if (activePart instanceof IEditorPart) {
        IEditorInput input = (IEditorInput) evalContext.getVariable(ISources.ACTIVE_EDITOR_INPUT_NAME);
        resources.add((IResource) input.getAdapter(IResource.class));
    } else {
        Object selection = evalContext.getVariable(ISources.ACTIVE_CURRENT_SELECTION_NAME);
        if (selection instanceof IStructuredSelection) {
            IStructuredSelection struct = (IStructuredSelection) selection;
            for (Object firstElement : struct.toList()) {
                if (firstElement instanceof IResource) {
                    resources.add((IResource) firstElement);
                } else if (firstElement instanceof IAdaptable) {
                    IAdaptable adaptable = (IAdaptable) firstElement;
                    resources.add((IResource) adaptable.getAdapter(IResource.class));
                }
            }
        }
    }
    return resources;
}

From source file:com.aptana.git.ui.internal.actions.CommitDialog.java

License:Open Source License

private Table createTable(Composite composite, final boolean staged) {
    Table table = new Table(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.FULL_SELECTION);
    table.setLinesVisible(true);//from   w ww. ja v a 2s  .  c o  m
    table.setHeaderVisible(true);
    GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
    data.heightHint = 200;
    data.widthHint = 250;
    table.setLayoutData(data);
    String[] titles = { " ", Messages.CommitDialog_PathColumnLabel }; //$NON-NLS-1$
    int[] widths = new int[] { 20, 250 };
    for (int i = 0; i < titles.length; i++) {
        TableColumn column = new TableColumn(table, SWT.NONE);
        column.setText(titles[i]);
        column.setWidth(widths[i]);
    }
    List<ChangedFile> changedFiles = gitRepository.index().changedFiles();
    Collections.sort(changedFiles);
    for (ChangedFile file : changedFiles) {
        boolean match = false;
        if (staged && file.hasStagedChanges()) {
            match = true;
        } else if (!staged && file.hasUnstagedChanges()) {
            match = true;
        }

        if (match) {
            createTableItem(table, file, false);
        }
    }

    // Drag and Drop
    // FIXME If user drags and drops while we're still crunching on last drag/drop then we end up hanging
    // Seems to be related to manipulating the table here before we receive the index changed callback
    Transfer[] types = new Transfer[] { LocalSelectionTransfer.getTransfer() };

    // Drag Source
    DragSource source = new DragSource(table, DND.DROP_MOVE);
    source.setTransfer(types);
    source.addDragListener(new DragSourceAdapter() {
        public void dragStart(DragSourceEvent event) {
            DragSource ds = (DragSource) event.widget;
            draggingFromTable = ds.getControl();

            LocalSelectionTransfer.getTransfer()
                    .setSelection(new StructuredSelection(((Table) draggingFromTable).getSelection()));
            LocalSelectionTransfer.getTransfer().setSelectionSetTime(event.time & 0xFFFFFFFFL);
        }

        public void dragSetData(DragSourceEvent event) {
            // do nothing
        }
    });

    // Create the drop target
    DropTarget target = new DropTarget(table, DND.DROP_MOVE);
    target.setTransfer(types);
    if (table.getItemCount() == 0)
        target.setDropTargetEffect(null);
    target.addDropListener(new DropTargetAdapter() {
        public void dropAccept(DropTargetEvent event) {
            DropTarget dp = (DropTarget) event.widget;
            if (dp.getControl() == draggingFromTable) {
                event.detail = DND.DROP_NONE;
            }
        }

        public void dragEnter(DropTargetEvent event) {
            // Allow dropping text only
            for (int i = 0, n = event.dataTypes.length; i < n; i++) {
                if (LocalSelectionTransfer.getTransfer().isSupportedType(event.dataTypes[i])) {
                    event.currentDataType = event.dataTypes[i];
                }
            }
            event.operations = DND.DROP_MOVE;
        }

        public void dragOver(DropTargetEvent event) {
            event.feedback = DND.FEEDBACK_SCROLL;
        }

        @SuppressWarnings("unchecked")
        public void drop(DropTargetEvent event) {
            if (!LocalSelectionTransfer.getTransfer().isSupportedType(event.currentDataType))
                return;
            // Get the dropped data
            IStructuredSelection selection = (IStructuredSelection) event.data;
            moveItems(!staged, ((List<TableItem>) selection.toList()).toArray(new TableItem[selection.size()]));
        }
    });

    table.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            super.widgetSelected(e);
            if (e.item == null)
                return;
            TableItem item = (TableItem) e.item;
            updateDiff(staged, getChangedFile(item));
        }
    });
    // Allow double-clicking to toggle staged/unstaged
    table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseDown(MouseEvent e) {
            if (e.getSource() == null)
                return;
            Table table = (Table) e.getSource();
            Point point = new Point(e.x, e.y);
            TableItem item = table.getItem(point);
            if (item == null) {
                return;
            }
            // did user click on file image? If so, toggle staged/unstage
            Rectangle imageBounds = item.getBounds(0);
            if (imageBounds.contains(point)) {
                moveItems(staged, new TableItem[] { item });
            }
        }

        @Override
        public void mouseDoubleClick(MouseEvent e) {
            if (e.getSource() == null)
                return;
            Table table = (Table) e.getSource();
            TableItem[] selected = table.getSelection();
            moveItems(staged, selected);
        }
    });
    // Custom drawing so we can truncate filepaths in middle...
    table.addListener(SWT.EraseItem, new Listener() {

        public void handleEvent(Event event) {
            // Only draw the text custom
            if (event.index != 1)
                return;

            event.detail &= ~SWT.FOREGROUND;
        }
    });
    table.addListener(SWT.PaintItem, new Listener() {

        public void handleEvent(Event event) {
            // Only draw the text custom
            if (event.index != 1)
                return;
            TableItem item = (TableItem) event.item;
            String text = item.getText(event.index);

            // Truncate middle of string
            Table theTable = (Table) event.widget;
            int width = theTable.getColumn(event.index).getWidth();
            Point p = event.gc.stringExtent(text); // is text wider than available width?
            if (p.x > width) {
                // chop string in half and drop a few characters
                int middle = text.length() / 2;
                String beginning = text.substring(0, middle - 1);
                String end = text.substring(middle + 2, text.length());
                // Now repeatedly chop off one char from each end until we fit
                // TODO Chop each side separately? it'd take more loops, but text would fit tighter when uneven
                // lengths work better..
                while (event.gc.stringExtent(beginning + "..." + end).x > width) //$NON-NLS-1$
                {
                    if (beginning.length() > 0) {
                        beginning = beginning.substring(0, beginning.length() - 1);
                    } else {
                        break;
                    }
                    if (end.length() > 0) {
                        end = end.substring(1);
                    } else {
                        break;
                    }
                }
                text = beginning + "..." + end; //$NON-NLS-1$
            }
            event.gc.drawText(text, event.x, event.y, true);

            event.detail &= ~SWT.FOREGROUND;
        }
    });

    if (!staged) {
        final Table myTable = table;
        MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
        menuMgr.setRemoveAllWhenShown(true);
        menuMgr.addMenuListener(new IMenuListener() {
            public void menuAboutToShow(IMenuManager manager) {
                TableItem[] selected = myTable.getSelection();
                List<IResource> files = new ArrayList<IResource>();
                final List<ChangedFile> changedFiles = new ArrayList<ChangedFile>();
                for (TableItem item : selected) {
                    ChangedFile file = getChangedFile(item);
                    if (file != null) {
                        changedFiles.add(file);
                        IFile iFile = gitRepository.getFileForChangedFile(file);
                        if (iFile != null) {
                            files.add(iFile);
                        }
                    }
                }

                ContributionItem ci = new ContributionItem() {
                    public void fill(Menu menu, int index) {
                        MenuItem item = new MenuItem(menu, SWT.NONE);
                        item.setText(Messages.CommitDialog_RevertLabel);
                        // need to remove the file(s) from staged table once action runs
                        item.addSelectionListener(new SelectionAdapter() {
                            @Override
                            public void widgetSelected(SelectionEvent e) {
                                // need to make a copy because operation will actually change input files.
                                final List<ChangedFile> copy = new ArrayList<ChangedFile>(changedFiles);
                                for (ChangedFile cf : changedFiles) {
                                    copy.add(new ChangedFile(cf));
                                }

                                gitRepository.index().discardChangesForFiles(changedFiles);

                                PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {

                                    public void run() {
                                        // If this file was shown in diff area, we need to blank the diff area!
                                        if (fLastDiffFile != null) {
                                            for (ChangedFile file : copy) {
                                                if (file != null && file.equals(fLastDiffFile)) {
                                                    updateDiff(null, Messages.CommitDialog_NoFileSelected);
                                                }
                                            }
                                        }
                                        removeDraggedFilesFromSource(unstagedTable, copy);
                                    }
                                });
                            }
                        });
                    }
                };
                manager.add(ci);
                // Other plug-ins can contribute there actions here
                manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
            }
        });
        Menu menu = menuMgr.createContextMenu(table);
        table.setMenu(menu);
    }

    return table;
}

From source file:com.aptana.ide.debug.internal.ui.launchConfigurations.HttpServerSettingsTab.java

License:Open Source License

private void removePaths() {
    IStructuredSelection selection = (IStructuredSelection) fListViewer.getSelection();
    Object first = selection.getFirstElement();
    int index = -1;
    for (int i = 0; i < elements.size(); i++) {
        Object object = elements.get(i);
        if (object.equals(first)) {
            index = i;/*w w w  .ja v  a  2s .c  o  m*/
            break;
        }
    }
    elements.removeAll(selection.toList());
    if (index > elements.size() - 1) {
        index = elements.size() - 1;
    }
    if (index >= 0) {
        fListViewer.setSelection(new StructuredSelection(elements.get(index)));
    }
    setDirty(true);
    updateLaunchConfigurationDialog();
}

From source file:com.aptana.js.debug.ui.internal.preferences.JSDetailFormattersPreferencePage.java

License:Open Source License

@SuppressWarnings("unchecked")
private void removeTypes() {
    Object[] list = formatters.toArray();
    IStructuredSelection selection = (IStructuredSelection) listViewer.getSelection();
    Object first = selection.getFirstElement();
    int index = -1;
    for (int i = 0; i < list.length; i++) {
        if (list[i].equals(first)) {
            index = i;//from  w  w w  . j  a  v  a 2s  . co  m
            break;
        }
    }

    removeDetailFormatters(
            (DetailFormatter[]) selection.toList().toArray(new DetailFormatter[selection.size()]));

    list = formatters.toArray();
    if (index > list.length - 1) {
        index = list.length - 1;
    }
    if (index >= 0) {
        listViewer.setSelection(new StructuredSelection(list[index]));
    }
}

From source file:com.arc.cdt.debug.seecode.ui.views.SeeCodeCommandView.java

License:Open Source License

@Override
protected void setEngineSource(IStructuredSelection selection) {
    super.setEngineSource(selection);
    fSelectedSession = null;/*from w  w w.j  a v a  2  s .c o m*/
    //If we're actually referencing the Launch (i.e. no particular target), and
    // we have a multi-process session, then send commands to the CMPD controller
    // so that they can be broadcast to every process, subject to focus qualifications.
    if (!selection.isEmpty()) {
        // At this point, we are NOT in the UI thread.
        Object element = selection.getFirstElement();
        if (element instanceof ILaunch) {
            fSelectedSession = computeSessionFrom(element);
        } else {
            fCommandProcs.clear();
            for (Object select : selection.toList()) {
                EngineInterface engine = Utilities.computeEngineFromSelection(select);
                if (engine != null) {
                    ICommandProcessor cp = getCommandProcessor(engine);
                    if (!fCommandProcs.contains(cp))
                        fCommandProcs.add(cp);
                }
            }
        }
    }
}

From source file:com.archimatetool.editor.diagram.DiagramEditorFindReplaceProvider.java

License:Open Source License

@SuppressWarnings("unchecked")
private List<EditPart> getSelectedEditParts() {
    IStructuredSelection selection = (IStructuredSelection) fGraphicalViewer.getSelection();
    return selection.toList();
}