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:de.bmw.yamaica.ide.ui.commands.AddYamaicaNature.java

License:Mozilla Public License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbench workbench = PlatformUI.getWorkbench();
    ISelection selection = workbench.getActiveWorkbenchWindow().getSelectionService().getSelection();

    if (selection instanceof IStructuredSelection) {
        IStructuredSelection structuredSelection = (IStructuredSelection) selection;

        for (Object selectedElement : structuredSelection.toList()) {
            if (selectedElement instanceof IProject) {
                ProjectWizard.addYamaicaSpecificProjectSettings((IProject) selectedElement,
                        new NullProgressMonitor());
            }//ww  w .j a v  a2 s  . c  om
        }
    }

    return null;
}

From source file:de.bmw.yamaica.ide.ui.commands.RemoveYamaicaNature.java

License:Mozilla Public License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbench workbench = PlatformUI.getWorkbench();
    ISelection selection = workbench.getActiveWorkbenchWindow().getSelectionService().getSelection();

    if (selection instanceof IStructuredSelection) {
        IStructuredSelection structuredSelection = (IStructuredSelection) selection;

        for (Object selectedElement : structuredSelection.toList()) {
            if (selectedElement instanceof IProject) {
                ProjectWizard.removeYamaicaSpecificProjectSettings((IProject) selectedElement,
                        new NullProgressMonitor());
            }//from www  . j  a v  a  2 s .c om
        }
    }

    return null;
}

From source file:de.fu_berlin.inf.jtourbus.actions.InsertJTourBusCommentAction.java

License:Open Source License

private IMember[] getSelectedMembers(IStructuredSelection selection) {
    List<?> elements = selection.toList();
    int nElements = elements.size();
    if (nElements > 0) {
        IMember[] res = new IMember[nElements];
        ICompilationUnit cu = null;//  w ww . ja v a 2s. c  o  m
        for (int i = 0; i < nElements; i++) {
            Object curr = elements.get(i);
            if (curr instanceof IMethod || curr instanceof IType || curr instanceof IField) {
                IMember member = (IMember) curr; // limit to methods,
                // types & fields

                if (i == 0) {
                    cu = member.getCompilationUnit();
                    if (cu == null) {
                        return null;
                    }
                } else if (!cu.equals(member.getCompilationUnit())) {
                    return null;
                }
                if (member instanceof IType && member.getElementName().length() == 0) {
                    return null; // anonymous type
                }
                res[i] = member;
            } else {
                return null;
            }
        }
        return res;
    }
    return null;
}

From source file:de.fu_berlin.inf.jtourbus.view.TourBusRoutesView.java

License:Open Source License

/**
 * This is a callback that will allow us to create the viewer and initialize
 * it./*from  w ww.  j  a va  2s.c  om*/
 * 
 * @JTourBusStop 0.0, Interaction, createPartControl - Entry Point of the
 *               plugin:
 * 
 * This is the setup-entry-point for this plugin. The Eclipse Platform calls
 * this method when it initializes this view.
 * 
 * The following connections between the classes get established here: - A
 * new treeviewer is created for showing the routes later on. - The
 * associated ContentProvider is created and connected to the viewer. - A
 * label provider is created and connected also. - The view-part subscribes
 * to selection listener here (so when the user selects something new we can
 * change our view)
 */
public void createPartControl(Composite parent) {

    fJavaProject = null;

    if (log != null) {
        log("START");
    }

    { // Create TreeViewer
        fViewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
        fContentProvider = new TourBusRoutesContentProvider(getViewSite());
        fViewer.setContentProvider(fContentProvider);
        fViewer.setLabelProvider(new TourBusRoutesLabelProvider());
        fViewer.setInput(getViewSite());

        // Selection Handling
        fViewer.addSelectionChangedListener(new ISelectionChangedListener() {

            public void selectionChanged(SelectionChangedEvent event) {
                Object obj = ((IStructuredSelection) event.getSelection()).getFirstElement();

                fActionNextStop.setEnabled(
                        obj instanceof BusStop && fContentProvider.fTourPlan.getNext((BusStop) obj) != null);
                fActionPreviousStop.setEnabled(obj instanceof BusStop
                        && fContentProvider.fTourPlan.getPrevious((BusStop) obj) != null);
            }
        });

        // Drag and Drop Handling
        int ops = DND.DROP_MOVE;

        Transfer[] types = new Transfer[] { LocalSelectionTransfer.getTransfer() };
        de.fu_berlin.inf.jtourbus.utility.ViewerDropAdapter vda = new de.fu_berlin.inf.jtourbus.utility.ViewerDropAdapter(
                fViewer) {

            public boolean performDrop(Object data) {

                IStructuredSelection selection = (IStructuredSelection) LocalSelectionTransfer.getTransfer()
                        .getSelection();

                @SuppressWarnings("unchecked")
                Vector<BusStop> stops = new Vector(selection.toList());

                BusStop target = (BusStop) getCurrentTarget();
                boolean before = getCurrentLocation() == ViewerDropAdapter.LOCATION_BEFORE;

                BusStop other = (before ? fContentProvider.fTourPlan.getPrevious(target)
                        : fContentProvider.fTourPlan.getNext(target));

                double delta;
                if (other == null) {
                    delta = (before ? -1.0 : 1.0);
                } else {
                    delta = (other.getStopNumber() - target.getStopNumber()) / (stops.size() + 1);
                }

                String targetRoute = target.getRoute();
                double targetStopNumber = target.getStopNumber();
                int i = 0;
                for (BusStop stop : stops) {
                    fContentProvider.fTourPlan.remove(stop);
                    stop.setRoute(targetRoute);
                    stop.setStopNumber(targetStopNumber + delta * ++i);
                    fContentProvider.fTourPlan.add(stop);
                }

                double d = 1;
                for (BusStop stop : fContentProvider.fTourPlan.routes.get(targetRoute)) {
                    if (stop.getStopNumber() != d) {
                        stop.setStopNumber(d);
                        if (!stops.contains(stop)) {
                            stops.add(stop);
                        }
                    }
                    d++;
                }

                UpdateStopsOperation op = new UpdateStopsOperation(stops);
                op.run();

                return true;
            }

            public boolean validateDrop(Object target, int operation, TransferData transferType) {
                return target instanceof BusStop;
            }
        };

        // We do care about DND-sorting in this case.
        vda.setFeedbackEnabled(true);

        fViewer.addDropSupport(ops, types, vda);

        fViewer.addDragSupport(ops, types, new DragSourceListener() {
            public void dragStart(DragSourceEvent arg0) {
                IStructuredSelection selection = (IStructuredSelection) fViewer.getSelection();

                arg0.doit = true;
                Iterator<?> i = selection.iterator();
                while (i.hasNext()) {
                    if (!(i.next() instanceof BusStop)) {
                        arg0.doit = false;
                        break;
                    }
                }
            }

            // List<BusStop> stops;

            public void dragSetData(DragSourceEvent arg0) {
                IStructuredSelection selection = (IStructuredSelection) fViewer.getSelection();
                // List<BusStop>stops = (List<BusStop>)selection.toList();
                LocalSelectionTransfer.getTransfer().setSelection(selection);
            }

            public void dragFinished(DragSourceEvent arg0) {
                // Not needed because of incremental update
                // fActionRefresh.run();
            }
        });
    }

    makeActions();
    hookActions(getViewSite().getActionBars().getToolBarManager());
    hookContextMenu();

}

From source file:de.fu_berlin.inf.jtourbus.view.TourBusRoutesView.java

License:Open Source License

private void makeActions() {

    { // Refresh//from   ww w  .j  a va2  s.c  o m
        fActionRefresh = new Action() {

            public void run() {
                log("REFRESH");
                BusStop oldStop = getSelectedBusStop();
                fViewer.setInput(fJavaProject);
                if (oldStop != null) {
                    Set<BusStop> ts = fContentProvider.fTourPlan.routes.get(oldStop.getRoute());
                    if (ts != null) {
                        Iterator<BusStop> i = ts.iterator();
                        BusStop bs = null;
                        while (i.hasNext()) {
                            bs = i.next();
                            if (oldStop.getStopNumber() <= bs.getStopNumber()) {
                                break;
                            }
                        }

                        if (bs != null) {
                            fViewer.setSelection(new StructuredSelection(bs), true);
                        }
                    }
                }
            }
        };
        fActionRefresh.setText("Refresh BusTours");
        fActionRefresh.setToolTipText(
                "Updates the Bus Tour information from the current project. The list view will be updated to show the stops and routes of the project.");

        JavaPluginImages.setLocalImageDescriptors(fActionRefresh, "refresh_nav.gif");
    }

    { // Action for renaming tours

        fRenameTourAction = new Action() {

            public void renameTourStop(BusStop stop, String targetTour) {
                fContentProvider.fTourPlan.remove(stop);
                stop.setRoute(targetTour);
                fContentProvider.fTourPlan.add(stop);
            }

            public void run() {
                IStructuredSelection selection = ((IStructuredSelection) fViewer.getSelection());
                if (!selection.isEmpty()) {

                    Object o = selection.getFirstElement();
                    String tour = null;
                    if (o instanceof BusStop) {
                        tour = ((BusStop) o).getRoute();
                    } else {
                        tour = (String) o;
                    }

                    InputDialog inputBox = new InputDialog(getSite().getShell(), "Rename tour",
                            "Please enter the name of tour the selected stops are supposed to be on:", tour,
                            new IInputValidator() {
                                public String isValid(String newText) {
                                    newText = newText.trim();
                                    if ("".equals(newText) || newText == null) {
                                        return "Please enter a new tour name!";
                                    }
                                    if (newText.contains(",") || newText.contains("/*")
                                            || newText.contains("*/")) {
                                        return "Please don't \",\", " + "\"\\" + "*" + "\" or \"*"
                                                + "\\\" in tour names!";
                                    }
                                    return null;
                                }
                            });
                    inputBox.open();
                    if (inputBox.getReturnCode() == InputDialog.OK) {

                        String newTour = inputBox.getValue().trim();

                        List<BusStop> busStopsToWriteBack = new ArrayList<BusStop>();

                        for (Object selected : selection.toList()) {
                            if (selected instanceof BusStop) {
                                renameTourStop((BusStop) selected, newTour);
                                busStopsToWriteBack.add((BusStop) selected);
                            } else {
                                for (BusStop bs : new ArrayList<BusStop>(
                                        fContentProvider.fTourPlan.routes.get(selected))) {
                                    if (!busStopsToWriteBack.contains(bs)) {
                                        renameTourStop(bs, newTour);
                                        busStopsToWriteBack.add(bs);
                                    }
                                }
                            }
                        }

                        UpdateStopsOperation op = new UpdateStopsOperation(busStopsToWriteBack);
                        op.run();
                    }
                }
            }
        };
        fRenameTourAction.setText("&Rename tour");

        fRenameTourAction.setToolTipText("Rename a tour or move individual stops to other tour.");
    }

    { // Action for setting the current project form the active editor

        fActionSetFromEditor = new Action() {
            public void run() {
                IJavaProject project = Utilities.getProject(fLastSelection);
                if (project != null) {
                    fJavaProject = project;
                }
                fActionRefresh.run();

            }
        };
        fActionSetFromEditor.setText("(Re)build Tours");
        fActionSetFromEditor.setToolTipText(
                "Will determine the project you are working on and build tours by scanning this project.");

        JavaPluginImages.setLocalImageDescriptors(fActionSetFromEditor, "refresh_nav.gif");

        /**
         * @JTourBusStop 2, Interaction, selectionChanged
         * 
         * This Listener tracks the previously selected JavaElement in the
         * whole Eclipse page.
         * 
         * We track these changes, since when the action above is triggered
         * we would like to know which element has been selected.
         */
        getViewSite().getPage().addSelectionListener(new ISelectionListener() {
            public void selectionChanged(IWorkbenchPart part, ISelection selection) {

                if (selection != null && selection instanceof IStructuredSelection)
                    fLastSelection = (IStructuredSelection) selection;
            }
        });

    }

    { // Actions for moving to next and previous stop

        fActionNextStop = new Action() {
            public void run() {
                BusStop currentStop = getSelectedBusStop();
                if (currentStop != null) {
                    BusStop stop = fContentProvider.fTourPlan.getNext(currentStop);
                    fViewer.setSelection(new StructuredSelection(stop), true);
                    showStop(stop);
                }
            }
        };

        fActionNextStop.setText("Move cursor to next stop");
        fActionNextStop.setToolTipText("Moves the cursor to the next stop on the tour.");
        IconManager.setImageDescriptors(fActionNextStop, IconManager.NEXT);
        fActionNextStop.setEnabled(false);

        fActionPreviousStop = new Action() {
            public void run() {

                BusStop currentStop = getSelectedBusStop();
                if (currentStop != null) {
                    BusStop stop = fContentProvider.fTourPlan.getPrevious(currentStop);
                    fViewer.setSelection(new StructuredSelection(stop), true);
                    showStop(stop);
                }
            }
        };
        fActionPreviousStop.setText("Move cursor to previous stop");
        fActionPreviousStop.setToolTipText("Moves the cursor to the previous stop on the tour.");
        fActionPreviousStop.setEnabled(false);

        IconManager.setImageDescriptors(fActionPreviousStop, IconManager.PREVIOUS);
    }

    { // Action for insert a bus stop in the current editor
        fActionInsertBusStop = new InsertJTourBusCommentAction(getSite()) {
            public void run() {
                ISelection selection = null;
                try {
                    selection = JavaPlugin.getActivePage().getActiveEditor().getEditorSite()
                            .getSelectionProvider().getSelection();
                } catch (Exception e) {
                    // If there is no selection. Then just do nothing.
                    return;
                }
                BusStop currentStop = getSelectedBusStop();
                setCurrentStop(currentStop);

                if (selection instanceof ITextSelection) {
                    run((ITextSelection) selection, (JavaEditor) JavaPlugin.getActivePage().getActiveEditor()
                            .getAdapter(JavaEditor.class));
                }
                fContentProvider.fTourChangeListener.notifyView = true;
            }
        };

        IconManager.setImageDescriptors(fActionInsertBusStop, IconManager.STOP);
    }

    { // Add handler for double click
        fViewer.addDoubleClickListener(new IDoubleClickListener() {
            public void doubleClick(DoubleClickEvent event) {
                fDoubleClickAction.run();
            }
        });
    }
}

From source file:de.jaret.util.ui.timebars.swt.TimeBarViewer.java

License:Open Source License

/**
 * Set the selection in the timebar viewer according to a structured selection.
 * /*from  www .  ja v a2  s  .  c o m*/
 * @param selection structured selection to set
 */
private void setStructuredSelection(ISelection selection) {
    TimeBarSelectionModel tmSelection = new TimeBarSelectionModelImpl();
    if (selection instanceof IStructuredSelection) {
        IStructuredSelection structured = (IStructuredSelection) selection;
        for (Object o : structured.toList()) {
            if (o instanceof Interval) {
                tmSelection.addSelectedInterval((Interval) o);
            } else if (o instanceof TimeBarRow) {
                tmSelection.addSelectedRow((TimeBarRow) o);
            } else if (o instanceof IIntervalRelation) {
                tmSelection.addSelectedRelation((IIntervalRelation) o);
            } else {
                throw new IllegalArgumentException(
                        "Type " + o.getClass().getName() + " not supported for selection");
            }
        }
    }
    setSelectionModel(tmSelection);

}

From source file:de.marw.cdt.cmake.core.ui.DefinesViewer.java

License:Open Source License

private void handleDefineDelButton(TableViewer tableViewer) {
    final IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
    final Shell shell = tableViewer.getControl().getShell();
    if (MessageDialog.openQuestion(shell, "CMake-Define deletion confirmation",
            "Are you sure to delete the selected CMake-defines?")) {
        @SuppressWarnings("unchecked")
        ArrayList<CmakeDefine> defines = (ArrayList<CmakeDefine>) tableViewer.getInput();
        defines.removeAll(selection.toList());
        tableViewer.remove(selection.toArray());// updates the display
    }// w w  w  .  j  av  a  2s  .  c  o m
}

From source file:de.marw.cdt.cmake.core.ui.UnDefinesViewer.java

License:Open Source License

private void handleUnDefineDelButton(TableViewer tableViewer) {
    final IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
    final Shell shell = tableViewer.getControl().getShell();
    if (MessageDialog.openQuestion(shell, "CMake-Undefine deletion confirmation",
            "Are you sure to delete the selected CMake-undefines?")) {
        @SuppressWarnings("unchecked")
        ArrayList<String> undefines = (ArrayList<String>) tableViewer.getInput();
        undefines.removeAll(selection.toList());
        tableViewer.remove(selection.toArray());// updates the display
    }/*from  w  ww .  j  a va  2 s.c  o m*/
}

From source file:de.monticore.editorconnector.GraphicalSelectionListener.java

License:Open Source License

/**
 * <p>/*w  w  w  .  j a va2 s  . c  o  m*/
 * Sets the text selection in a {@link TextEditorImpl} according to the selected
 * {@link GraphicalEditPart GraphicalEditParts} in the {@link IStructuredSelection}.
 * </p>
 * <p>
 * The selection is set according to the editpart {@link TextPosition TextPositions}. <br>
 * <br>
 * If only one is selected, the selection is precisely only the {@link TextPosition}.<br>
 * If more than one is selected, the selection goes from the lowest start position to the highest
 * end position in the text editor.
 * </p>
 * 
 * @param ss The {@link IStructuredSelection} containing the selected {@link GraphicalEditPart
 * GraphicalEditParts}.
 * @param editor The {@link TextEditorImpl} to set the text selection in.
 */
@SuppressWarnings("unchecked")
private void setSelection(IStructuredSelection ss, TextEditorImpl editor) {
    List<Object> selectionList = ss.toList();

    // if there is more than one element selected select all
    // from minimum line number with minimum offset
    // to maximum line number with maximum offset
    // works also for only one element selected

    int startLine = Integer.MAX_VALUE;
    int startOffset = Integer.MAX_VALUE;
    int endLine = Integer.MIN_VALUE;
    int endOffset = Integer.MIN_VALUE;

    boolean setOnce = false;

    for (Object o : selectionList) {
        if (o instanceof IMCGraphicalEditPart) {
            IMCGraphicalEditPart ep = (IMCGraphicalEditPart) o;

            if (!ep.isSelectable()) {
                continue;
            }
            if (ep.getModel() instanceof ASTNode) {
                ASTNode astNode = (ASTNode) ep.getModel();

                startLine = Math.min(startLine, astNode.get_SourcePositionStart().getLine());
                startOffset = Math.min(startOffset, astNode.get_SourcePositionStart().getColumn());
                endLine = Math.max(endLine, astNode.get_SourcePositionEnd().getLine());
                endOffset = Math.max(endOffset, astNode.get_SourcePositionEnd().getColumn());
                setOnce = true;
            }
        }
    }
    if (setOnce) {
        selectText(editor, new TextPosition(startLine, startOffset, endLine, endOffset));
    }
}

From source file:de.opalproject.vespucci.ui.handlers.DeleteEnsembleHandler.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);

    @SuppressWarnings("unchecked")
    final List<Ensemble> ensembleList = selection.toList();

    final RemoveEnsemblesFromSlicesChoiceWizard wizard = new RemoveEnsemblesFromSlicesChoiceWizard(
            ensembleList);/*  w w w.j a  v a  2s.  com*/

    // Launch delete wizard
    WizardDialog dialog = new WizardDialog(HandlerUtil.getActiveShell(event), wizard);
    dialog.open();

    return null;
}