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:gov.nasa.ensemble.core.plan.editor.context.PlanEditorContextMenuBuilder.java

License:Open Source License

public static void buildContextMenu(IMenuManager manager, IStructuredSelection selection) {
    if (ATTRIBUTES.isEmpty()) {
        return;/*from  www.java  2  s.c om*/
    }
    List<EPlanElement> elements = new ArrayList<EPlanElement>();
    for (Object object : selection.toList()) {
        if (object instanceof EPlanElement) {
            elements.add((EPlanElement) object);
        }
    }
    if (elements.isEmpty()) {
        return;
    }
    EPlanElement representative = elements.get(0);
    for (String attributeName : ATTRIBUTES) {
        EStructuralFeature feature = getFeature(elements, attributeName);
        if (feature != null) {
            String displayName = EMFUtils.getDisplayName(representative, feature);
            IItemPropertyDescriptor pd = getPropertyDescriptor(representative, feature);
            if (pd != null) {
                EClassifier eType = feature.getEType();
                if (eType == EcorePackage.Literals.EBOOLEAN || eType == EcorePackage.Literals.EBOOLEAN_OBJECT) {
                    manager.add(new BooleanAction(displayName, elements, feature));
                } else if (feature instanceof EReference || eType instanceof EEnum) {
                    ImageDescriptor icon = PlanEditorContextMenuIconProvider.getInstance().get(feature);
                    Collection<?> choiceOfValues = pd.getChoiceOfValues(representative);
                    MenuManager attributeMenu = new MenuManager(displayName, icon, null);
                    for (Object value : choiceOfValues) {
                        attributeMenu.add(new ValueAction(displayName, elements, feature, value));
                    }
                    manager.add(attributeMenu);
                } else {
                    LogUtil.warn(feature.getName() + " is not supported by plan editor context menu.");
                }
            }
        }
    }
    manager.add(new Separator());
}

From source file:gov.nasa.ensemble.core.plan.editor.view.template.actions.TemplatePlanViewDeleteItemAction.java

License:Open Source License

/**
 * Delete from the model each element in the StructuredSelection and save the resource.
 * @param structuredSelection//from   w w w .  j av  a2s  .c o  m
 */
public void delete(final IStructuredSelection structuredSelection) {
    final EPlan templatePlan = templatePlanView.getCurrentTemplatePlan();
    TransactionUtils.writing(templatePlan, new Runnable() {
        @Override
        public void run() {
            Set<Resource> resources = new HashSet<Resource>();
            List list = structuredSelection.toList();
            for (Object object : list) {
                if (object instanceof EObject) {
                    EObject eObject = (EObject) object;
                    if (eObject.eResource() == null)
                        continue;
                    closeOpenEditor(eObject);
                    List<EReference> containmentReferences = new ArrayList<EReference>(
                            eObject.eClass().getEAllContainments());
                    for (EReference eReference : containmentReferences) {
                        Object target = eObject.eGet(eReference, false);
                        if (eReference.isMany()) {
                            if (target instanceof InternalEList) {
                                InternalEList internalEList = (InternalEList) target;
                                for (Object value : internalEList) {
                                    if (value instanceof InternalEObject) {
                                        InternalEObject internalEObject = (InternalEObject) value;
                                        if (internalEObject.eResource() != eObject.eResource()) {
                                            resources.add(internalEObject.eResource());
                                            EcoreUtil.delete(internalEObject);
                                        }
                                    }
                                }
                            }

                        } else {
                            if (target instanceof InternalEObject) {
                                InternalEObject internalEObject = (InternalEObject) target;
                                if (internalEObject.eResource() != eObject.eResource()) {
                                    resources.add(internalEObject.eResource());
                                    EcoreUtil.delete(internalEObject);
                                }
                            }
                        }
                    }

                    performAdditionalCleanup(eObject);

                    EcoreUtil.delete(eObject);
                }
            }

            TemplatePlanUtils.saveTemplatePlan(templatePlan);
            for (Resource resource : resources) {
                TemplatePlanUtils.saveTemplateResource(resource);
            }
        }
    });
}

From source file:gov.nasa.ensemble.core.plan.editor.view.template.TemplatePlanUtils.java

License:Open Source License

/**
 * Returns all folder models contained in the selection. If any non model items are found, an empty collection is returned.
 * //from   ww w .ja  v  a  2s  . c o  m
 */
public static List<DynamicEObjectImpl> getAllFolderModels(IStructuredSelection structuredSelection) {
    List<DynamicEObjectImpl> models = new ArrayList<DynamicEObjectImpl>();
    List list = structuredSelection.toList();
    for (Object object : list) {
        if (object instanceof IAdaptable) {
            IAdaptable adaptable = (IAdaptable) object;
            Object adapter = adaptable.getAdapter(DynamicEObjectImpl.class);
            if (adapter instanceof DynamicEObjectImpl) {
                models.add((DynamicEObjectImpl) adapter);
            } else {
                return Collections.emptyList();
            }
        }
    }
    return models;
}

From source file:gov.nasa.ensemble.tests.core.plan.editor.TestCopyPasteManyTimesOperation.java

License:Open Source License

private void assertCorrectFinalSelection(IStructuredSelection targetSelection, int copies,
        ISelectionProvider selectionProvider) {
    final List actualSelection = ((IStructuredSelection) selectionProvider.getSelection()).toList();
    assertEquals("Expected to have selected " + copies + " copies of " + targetSelection + " but was "
            + actualSelection, targetSelection.size() * copies, actualSelection.size());
    for (Object object : targetSelection.toList())
        assertFalse(actualSelection.contains(object));
}

From source file:gov.redhawk.eclipsecorba.library.internal.ResetLibraryFileHandler.java

License:Open Source License

/**
 * {@inheritDoc}//from ww w . j ava 2s  .c o m
 */
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
    final ISelection selection = HandlerUtil.getActiveMenuSelection(event);
    if (selection instanceof IStructuredSelection) {
        final IStructuredSelection structuredSelection = (IStructuredSelection) selection;
        for (final Object obj : structuredSelection.toList()) {
            final IProject project = getAdapter(IProject.class, obj);
            if (project != null) {
                final IFile libraryFile = project.getFile(".library");
                final WorkspaceJob job = new WorkspaceJob("Reset IDL File " + libraryFile) {

                    @Override
                    public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException {
                        ResourceUtils.createIdlLibraryResource(libraryFile, monitor);
                        return Status.OK_STATUS;
                    }
                };
                if (libraryFile.exists()) {
                    job.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().modifyRule(libraryFile));
                } else {
                    job.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().createRule(libraryFile));
                }
                job.setSystem(true);
                job.schedule();
            }
        }
    }
    return null;
}

From source file:gov.redhawk.frontend.ui.internal.ConnectTunerHandler.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    // need to grab Port selections first, otherwise Plot Wizard option below will change the selection
    IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveMenuSelection(event);
    if (selection == null) {
        selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
        if (selection == null) {
            return null;
        }//w  w  w.  j a v a 2  s. co  m
    }

    final List<?> elements = selection.toList();

    for (Object obj : elements) {
        if (obj instanceof TunerStatus) {
            final TunerStatus tuner = (TunerStatus) obj;
            final ScaDevice<?> device = ScaEcoreUtils.getEContainerOfType(tuner, ScaDevice.class);
            List<ScaPort<?, ?>> devicePorts = device.getPorts();
            final List<ScaUsesPort> usesPorts = new ArrayList<ScaUsesPort>();
            for (ScaPort<?, ?> port : devicePorts) {
                if (port instanceof ScaUsesPort) {
                    usesPorts.add((ScaUsesPort) port);
                }
            }
            if (usesPorts.isEmpty()) {
                Status status = new Status(IStatus.ERROR, FrontEndUIActivator.PLUGIN_ID,
                        "No output ports available, can not make a connection from " + tuner.getTunerID(),
                        new Exception().fillInStackTrace());
                StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW);
                return null;
            }

            ConnectTunerWizard wizard = new ConnectTunerWizard();
            wizard.setTuner(tuner);
            WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), wizard);
            dialog.open();
        }
    }
    return null;
}

From source file:gov.redhawk.frontend.ui.internal.FeiPlotHandler.java

License:Open Source License

@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
    // need to grab Port selections first, otherwise Plot Wizard option below will change the selection
    IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveMenuSelection(event);
    if (selection == null) {
        selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
        if (selection == null) {
            return null;
        }//w  w  w. j  a  va  2 s  .c o  m
    }

    final List<?> elements = selection.toList();
    String listenerAllocationID = "Plot_" + ConnectPortWizard.generateDefaultConnectionID();

    for (Object obj : elements) {
        if (obj instanceof TunerStatus) {
            final TunerStatus tuner = (TunerStatus) obj;
            final ScaDevice<?> device = ScaEcoreUtils.getEContainerOfType(tuner, ScaDevice.class);
            List<ScaPort<?, ?>> devicePorts = device.getPorts();
            final List<ScaUsesPort> usesPorts = new ArrayList<ScaUsesPort>();
            for (ScaPort<?, ?> port : devicePorts) {
                if (port instanceof ScaUsesPort && PlotPortHandler.isBulkIOPortSupported(port.getRepid())) {
                    usesPorts.add((ScaUsesPort) port);
                }
            }
            if (usesPorts.isEmpty()) {
                Status status = new Status(IStatus.ERROR, FrontEndUIActivator.PLUGIN_ID,
                        "No valid BulkIO output ports available, can not plot from " + tuner.getTunerID(),
                        new Exception().fillInStackTrace());
                StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW);
                continue;
            }

            final DataType[] props = TunerStatusUtil.createAllocationProperties(listenerAllocationID, tuner);

            final UIJob uiJob = new UIJob("Launching Plot View...") {

                @Override
                public IStatus runInUIThread(IProgressMonitor monitor) {
                    try {
                        IStatus retVal = createPlotView(event, props, device, tuner, usesPorts);
                        if (!retVal.isOK()) {
                            TunerStatusUtil.createDeallocationJob(tuner, props).schedule();
                        }

                        return retVal;
                    } catch (ExecutionException e) {
                        TunerStatusUtil.createDeallocationJob(tuner, props).schedule();
                        return new Status(IStatus.ERROR, FrontEndUIActivator.PLUGIN_ID,
                                "Failed to open plot view", e);
                    }
                }

            };

            Job allocJob = TunerStatusUtil.createAllocationJob(tuner, props);
            allocJob.addJobChangeListener(new JobChangeAdapter() {
                @Override
                public void done(IJobChangeEvent event) {
                    if (event.getResult().isOK()) {
                        uiJob.setUser(false);
                        uiJob.setSystem(true);
                        uiJob.schedule();
                    }
                }
            });
            allocJob.setUser(true);
            allocJob.schedule();

        }
    }

    return null;
}

From source file:gov.redhawk.frontend.ui.internal.FeiSriHandler.java

License:Open Source License

@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
    window = HandlerUtil.getActiveWorkbenchWindow(event);

    // Launches from the plot view menu
    IWorkbenchPart activePart = HandlerUtil.getActivePart(event);
    if (activePart instanceof IPlotView) {
        IPlotView plotView = (IPlotView) HandlerUtil.getActivePart(event);
        List<PlotSource> sources = plotView.getPlotPageBook().getSources();
        for (PlotSource source : sources) {
            final ScaUsesPort usesPort = source.getInput();
            final String connectionId = source.getBulkIOBlockSettings().getConnectionID();
            IStatus retVal = displaySriView(event, usesPort, connectionId);
            return retVal;
        }//from w  ww .java 2 s  . com
    }

    // Launches from a context menu selection
    IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveMenuSelection(event);
    if (selection == null) {
        selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
        if (selection == null) {
            return null;
        }
    }

    final List<?> elements = selection.toList();
    if (elements.isEmpty()) {
        return null;
    }

    for (Object obj : elements) {
        if (obj instanceof TunerStatus) {
            // Get the tuner
            final TunerStatus tuner = (TunerStatus) obj;
            // Get the containing device for the tuner
            final ScaDevice<?> device = ScaEcoreUtils.getEContainerOfType(tuner, ScaDevice.class);

            // Create the allocation property structure
            final DataType[] props = createAllocationProperties(tuner);

            // Core Job that handles capacity allocation and displaying the view
            Job job = new Job("Displaying SRI Data for " + tuner.getAllocationID()) {
                @Override
                protected IStatus run(IProgressMonitor parentMonitor) {
                    final SubMonitor subMonitor = SubMonitor.convert(parentMonitor,
                            "Displaying SRI Data for " + tuner.getAllocationID(), IProgressMonitor.UNKNOWN);

                    try {
                        // First check to see if a SRI View is already listening on this tuner
                        for (ListenerAllocation listener : tuner.getListenerAllocations()) {
                            if (listener.getListenerID().startsWith("SRI")) {
                                return Status.OK_STATUS;
                            }
                        }

                        // Allocate capacity on the device for the listener if no SRI View is found
                        IStatus status = CorbaUtils.invoke(new Callable<IStatus>() {
                            @Override
                            public IStatus call() throws Exception {
                                try {
                                    subMonitor.subTask("Allocating capacity...");
                                    if (device.allocateCapacity(props)) {
                                        return Status.OK_STATUS;
                                    } else {
                                        return new Status(IStatus.ERROR, FrontEndUIActivator.PLUGIN_ID,
                                                "Allocation failed, SRI data could not display.", null);
                                    }
                                } catch (InvalidCapacity e) {
                                    return new Status(IStatus.ERROR, FrontEndUIActivator.PLUGIN_ID,
                                            "Invalid Capacity in SRI View allocation: " + e.msg, e);
                                } catch (InvalidState e) {
                                    return new Status(IStatus.ERROR, FrontEndUIActivator.PLUGIN_ID,
                                            "Invalid State in SRI View allocation: " + e.msg, e);
                                } catch (InsufficientCapacity e) {
                                    return new Status(IStatus.ERROR, FrontEndUIActivator.PLUGIN_ID,
                                            "Insufficient Capacity in SRI View allocation: " + e.msg, e);
                                }
                            }
                        }, subMonitor.newChild(1));
                        if (!status.isOK()) {
                            return status;
                        }
                        subMonitor.subTask("Refreshing device...");
                        device.refresh(subMonitor.newChild(1), RefreshDepth.SELF);
                    } catch (InterruptedException e) {
                        return Status.CANCEL_STATUS;
                    } catch (CoreException e) {
                        return new Status(e.getStatus().getSeverity(), FrontEndUIActivator.PLUGIN_ID,
                                "Failed to allocate for SRI", e);
                    } finally {
                        subMonitor.done();
                    }

                    // Display the SRI View
                    UIJob uiJob = new UIJob("Launching SRI View...") {
                        @Override
                        public IStatus runInUIThread(IProgressMonitor monitor) {
                            try {
                                IStatus retVal = createSriView(event, props, elements, device, tuner);

                                // If the view was not created successfully then deallocate
                                if (!retVal.isOK()) {
                                    deallocate(tuner, props, device);
                                }
                                return retVal;
                            } catch (ExecutionException e) {
                                deallocate(tuner, props, device);
                                return new Status(IStatus.ERROR, FrontEndUIActivator.PLUGIN_ID,
                                        "Failed to open SRI Data View", e);
                            }
                        }
                    };
                    uiJob.setUser(false);
                    uiJob.setSystem(true);
                    uiJob.schedule();
                    return Status.OK_STATUS;
                }
            };
            job.setUser(true);
            job.schedule();
        }
    }
    return null;
}

From source file:gov.redhawk.ide.codegen.ui.internal.command.ExportResourceHandler.java

License:Open Source License

@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
    final ISelection selection = HandlerUtil.getActiveMenuSelection(event);

    if (selection instanceof IStructuredSelection) {
        final IStructuredSelection ss = (IStructuredSelection) selection;

        for (final Object obj : ss.toList()) {
            final IFile file = (IFile) obj;

            final IProject project = file.getProject();

            final WorkspaceJob job = new WorkspaceJob("Exporting SCA Resource") {

                @Override/*from  w  w w.ja  va2s .  c  o  m*/
                public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException {
                    try {
                        if (project.hasNature(ScaNodeProjectNature.ID)) {
                            ExportUtils.exportNode(project, ExportResourceHandler.this.exporter,
                                    new NullProgressMonitor());
                        } else if (project.hasNature(ScaComponentProjectNature.ID)) {
                            ExportUtils.exportComponent(project, ExportResourceHandler.this.exporter,
                                    new NullProgressMonitor());
                        } else if (project.hasNature(ScaWaveformProjectNature.ID)) {
                            ExportUtils.exportWaveform(project, ExportResourceHandler.this.exporter,
                                    new NullProgressMonitor());
                        }

                        ExportResourceHandler.this.exporter.finished();
                    } catch (final CoreException e) {
                        StatusManager.getManager().handle(e, RedhawkCodegenUiActivator.PLUGIN_ID);
                    } catch (final java.io.IOException e) {
                        StatusManager
                                .getManager().handle(
                                        new Status(IStatus.ERROR, RedhawkCodegenUiActivator.PLUGIN_ID,
                                                "Failed to export.", e),
                                        StatusManager.LOG | StatusManager.SHOW);
                    }

                    return Status.OK_STATUS;
                }
            };
            job.setPriority(Job.LONG);
            job.setUser(true);
            job.setSystem(false);
            job.schedule();
        }
    }
    return null;
}

From source file:gov.redhawk.ide.codegen.ui.internal.command.GenerateCodeHandler.java

License:Open Source License

@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {

    // GenerateCode Class simply takes an object to generate from. It should be either a list of implementations, an
    // implementation or IFile

    // If the user used a context menu, generate code on the selection(s)
    final ISelection selection = HandlerUtil.getActiveMenuSelection(event);

    // for each of the elements in the selection
    // if its empty or null then its the editor (IFile)
    // if its not empty / null then it should be either an Implementation or an IFile.
    // We need to get the project so we can save related resources.
    // Fom the IFile its easy, from the implementation we need to get the EMF Resource and get the IFile from there

    // If the menu selection is empty then Generate button was pressed within the editor
    if (selection == null || selection.isEmpty()) {
        final IEditorPart editor = HandlerUtil.getActiveEditor(event);
        if (editor != null) {
            if (editor instanceof SCAFormEditor) {
                SCAFormEditor scaEditor = (SCAFormEditor) editor;
                SoftPkg spd = SoftPkg.Util.getSoftPkg(scaEditor.getMainResource());
                if (spd != null) {
                    IProject project = ModelUtil.getProject(spd);
                    try {
                        saveAndGenerate(spd, project, HandlerUtil.getActiveShell(event));
                    } catch (CoreException e) {
                        StatusManager.getManager()
                                .handle(new Status(e.getStatus().getSeverity(),
                                        RedhawkCodegenUiActivator.PLUGIN_ID, e.getLocalizedMessage(), e),
                                        StatusManager.SHOW | StatusManager.LOG);
                        return null;
                    }/*from   w w  w.j ava  2 s. c o m*/
                    return null;
                }
            } else {
                final IEditorInput editorInput = editor.getEditorInput();
                if (editorInput instanceof IFileEditorInput) {
                    final IFile f = ((IFileEditorInput) editorInput).getFile();
                    if (isSpdFile(f)) {
                        try {
                            saveAndGenerate(f, f.getProject(), HandlerUtil.getActiveShell(event));
                        } catch (CoreException e) {
                            StatusManager.getManager()
                                    .handle(new Status(e.getStatus().getSeverity(),
                                            RedhawkCodegenUiActivator.PLUGIN_ID, e.getLocalizedMessage(), e),
                                            StatusManager.SHOW | StatusManager.LOG);
                            return null;
                        }
                        return null;
                    }
                }
            }
        }
    } else { // The selection was made either via the right click menu from the Project Explorer, or in the
             // Implementations tab.
        if (selection instanceof IStructuredSelection) {
            final IStructuredSelection ss = (IStructuredSelection) selection;

            for (Object obj : ss.toList()) {
                if (obj instanceof IFile && isSpdFile((IFile) obj)) {
                    try {
                        saveAndGenerate(obj, ((IFile) obj).getProject(), HandlerUtil.getActiveShell(event));
                    } catch (CoreException e) {
                        StatusManager.getManager()
                                .handle(new Status(e.getStatus().getSeverity(),
                                        RedhawkCodegenUiActivator.PLUGIN_ID, e.getLocalizedMessage(), e),
                                        StatusManager.SHOW | StatusManager.LOG);
                        return null;
                    }
                } else if (obj instanceof Implementation) {
                    Implementation impl = (Implementation) obj;
                    String platformURI = impl.eResource().getURI().toPlatformString(true);
                    IResource spdFile = ResourcesPlugin.getWorkspace().getRoot().findMember(platformURI);

                    if (spdFile instanceof IFile && isSpdFile((IFile) spdFile)) {
                        try {
                            saveAndGenerate(impl, ((IFile) spdFile).getProject(),
                                    HandlerUtil.getActiveShell(event));
                        } catch (CoreException e) {
                            StatusManager.getManager()
                                    .handle(new Status(e.getStatus().getSeverity(),
                                            RedhawkCodegenUiActivator.PLUGIN_ID, e.getLocalizedMessage(), e),
                                            StatusManager.SHOW | StatusManager.LOG);
                            return null;
                        }
                    }
                }
            }
            return null;
        }
    }

    // If we get here, somehow the generate code handler was triggered from somewhere it shouldn't be - log this
    RedhawkCodegenUiActivator.logError("Generate code handler was triggered without a valid selection", null);
    return null;
}