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:mx.itesm.imb.handlers.Util.java

License:Open Source License

/**
 * Get the current selected elements when a plugin operation is executed.
 * //from   w w w.  j  a va2s. c om
 * @param event
 * @return
 */
public static List<?> getSelectedItems(final ExecutionEvent event) {
    List<?> returnValue;
    IStructuredSelection currentSelection;

    currentSelection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
    returnValue = currentSelection.toList();

    return returnValue;
}

From source file:name.martingeisse.esdk.eclipse.EsdkNatureDelegate.java

License:Open Source License

@Override
public void run(final IAction action) {
    if (selection instanceof IStructuredSelection) {
        final IStructuredSelection structuredSelection = (IStructuredSelection) selection;
        for (final Object element : structuredSelection.toList()) {
            if (element instanceof IProject) {
                final IProject project = (IProject) element;
                if (action.getId()
                        .equals("name.martingeisse.esdk.ProjectPopupMenuContribution.AddEsdkNature")) {
                    addNature(project);/*from  ww  w  .j  a va 2s .  c o m*/
                } else if (action.getId()
                        .equals("name.martingeisse.esdk.ProjectPopupMenuContribution.RemoveEsdkNature")) {
                    deleteNature(project);
                } else {
                    Activator.getDefault()
                            .logWarning("EsdkNatureDelegate invoked for unknown action id: " + action.getId());
                }
            } else {
                Activator.getDefault()
                        .logWarning("EsdkNatureDelegate invoked for unknown target object: " + element);
            }
        }
    }
}

From source file:name.schedenig.eclipse.grepconsole.view.styles.StylesPanel.java

License:Open Source License

/**
 * Returns the selected styles./* w  ww .  j  a v a  2  s.  c  om*/
 * 
 * @return Styles. May be empty.
 */
public Collection<GrepStyle> getSelectedStyles() {
    List<GrepStyle> styles = new LinkedList<GrepStyle>();
    IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();

    if (selection != null) {
        for (Object o : selection.toList()) {
            if (o instanceof GrepStyle) {
                styles.add((GrepStyle) o);
            }
        }
    }

    return styles;
}

From source file:net.bhl.cdt.paxelerate.ui.handlers.MoveObjectHandler.java

License:Open Source License

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

    for (Object object : selection.toList()) {
        if (object instanceof Row) {
            rowlist.add((Row) object);//  w w  w  .  ja va 2s .  c o  m
        } else if (object instanceof Seat) {
            seatlist.add((Seat) object);
        } else if (object instanceof Galley) {
            galleylist.add((Galley) object);
        } else if (object instanceof Lavatory) {
            lavatorylist.add((Lavatory) object);
        } else if (object instanceof Curtain) {
            curtainlist.add((Curtain) object);
        } else {
            /* ignore other objects */
        }
    }
    if (!rowlist.isEmpty()) {
        cabin = ModelHelper.getParent(Cabin.class, rowlist.get(0));
    } else if (!seatlist.isEmpty()) {
        cabin = ModelHelper.getParent(Cabin.class, seatlist.get(0));
    } else if (!galleylist.isEmpty()) {
        cabin = ModelHelper.getParent(Cabin.class, galleylist.get(0));
    } else if (!lavatorylist.isEmpty()) {
        cabin = ModelHelper.getParent(Cabin.class, lavatorylist.get(0));
    } else if (!curtainlist.isEmpty()) {
        cabin = ModelHelper.getParent(Cabin.class, curtainlist.get(0));
    } else {
        cabin = null;
    }

    new MoveObjectCommand(cabin, rowlist, seatlist, galleylist, lavatorylist, curtainlist).execute();

    /*
     * clear all lists in order to prevent the unintentioal movement of
     * several items edited before
     */
    rowlist.clear();
    seatlist.clear();
    galleylist.clear();
    lavatorylist.clear();
    curtainlist.clear();

    return null;
}

From source file:net.bioclipse.align.kalign.ws.handlers.KalignPopupHandler.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {

    ISelection sel = HandlerUtil.getCurrentSelection(event);
    if (!(sel instanceof IStructuredSelection))
        return null;

    IStructuredSelection ssel = (IStructuredSelection) sel;

    final Shell shell = HandlerUtil.getActiveShell(event);

    final IBiojavaManager biojava = net.bioclipse.biojava.business.Activator.getDefault()
            .getJavaBiojavaManager();//from   ww w .jav a2  s .  c o  m

    final List<IProtein> proteins = new ArrayList<IProtein>();
    final List<String> names = new ArrayList<String>();
    IProject firstProject = null;
    for (Object obj : ssel.toList()) {
        if (obj instanceof IFile) {
            IFile file = (IFile) obj;
            if (firstProject == null)
                firstProject = file.getProject();
            try {

                List<IProtein> readProts = biojava.proteinsFromFile(file);

                proteins.addAll(readProts);
                String fname = file.getName();
                if (fname.lastIndexOf(".") > 0)
                    fname = fname.substring(0, fname.lastIndexOf("."));
                names.add(fname);
            } catch (FileNotFoundException e) {
                logger.error("Could not find file: " + file.getLocation());
            } catch (Exception e) {
                MessageDialog.openError(shell, "Kalign",
                        "Error parsing proteins. Make sure you have valid files!");
                return null;
            }
        }
    }

    if (firstProject == null) {
        MessageDialog.openError(shell, "Kalign", "No output project could be located.");
        return null;
    }

    if (proteins.size() <= 0) {
        MessageDialog.openError(shell, "Kalign", "No proteins could be parsed");
        return null;
    }
    if (proteins.size() == 0) {
        MessageDialog.openError(shell, "Kalign",
                "Only one protein could be parsed, " + "need a minimum of two proteins to align.");
        return null;
    }

    final IProject project = firstProject;

    Job job = new Job("Kalign") {

        @Override
        protected IStatus run(IProgressMonitor monitor) {

            IKalignManager kalign = Activator.getDefault().getKalignManager();
            List<IProtein> alignedProteins;
            try {
                alignedProteins = kalign.alignProteins(proteins, monitor);
            } catch (BioclipseException e) {
                LogUtils.handleException(e, logger, "net.bioclipse.align.kalign.ws");
                return Status.CANCEL_STATUS;
            }
            List<ISequence> alignedSequences = new ArrayList<ISequence>();
            for (ISequence seq : alignedProteins)
                alignedSequences.add(IProtein.class.cast(seq));

            //Generate a new filename
            String newFileName = "";
            for (String name : names) {
                newFileName = newFileName.concat(name + "_");
            }
            newFileName = newFileName.substring(0, newFileName.length() - 1);
            newFileName = newFileName.concat("_aligned.fasta");

            logger.debug("New alignment file to save: " + newFileName);

            //Serialize to temp file and open in SeqEditor
            IFile newfile = project.getFile(newFileName);
            if (newfile.exists()) {
                final Boolean[] ret = new Boolean[1];
                final String name = newFileName;
                final Boolean[] valueSet = new Boolean[] { false };

                Display.getDefault().asyncExec(new Runnable() {
                    public void run() {
                        synchronized (ret) {
                            ret[0] = MessageDialog.openConfirm(shell, "Overwrite?",
                                    "Resulting alignment file " + name + " exists. Overwrite?");
                        }
                        synchronized (valueSet) {
                            valueSet[0] = true;
                            valueSet.notifyAll();
                        }
                    }
                });

                while (!valueSet[0]) {
                    synchronized (valueSet) {
                        try {
                            valueSet.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException("Interruped", e);
                        }
                    }
                }
                if (ret[0] == false)
                    return Status.CANCEL_STATUS;
            }

            //Save aligned proteins to file
            biojava.proteinsToFASTAfile(alignedProteins, newfile);

            try {
                project.refreshLocal(1, new NullProgressMonitor());
            } catch (CoreException e) {
                //Not much we can do if refresh fails. Should not happen.
            }

            //Open saved file
            IUIManager ui = net.bioclipse.ui.business.Activator.getDefault().getUIManager();
            ui.open(newfile);

            return Status.OK_STATUS;
        }
    };
    job.setUser(true);
    job.schedule();

    return null;
}

From source file:net.bioclipse.balloon.handlers.BalloonConformerHandler.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {

    ISelection sel = HandlerUtil.getCurrentSelection(event);
    if (sel == null)
        return null;
    if (!(sel instanceof StructuredSelection))
        return null;
    IStructuredSelection ssel = (IStructuredSelection) sel;

    //We operate on files and IMolecules
    List<String> filenames = new ArrayList<String>();
    List<IResource> foldersToRefresh = new ArrayList<IResource>();
    //Collect files
    for (Object obj : ssel.toList()) {
        if (obj instanceof IFile) {
            IFile file = (IFile) obj;//from   w ww . j a  v  a 2s .  com
            //                filenames.add( file.getRawLocation().toOSString() );
            filenames.add(file.getFullPath().toOSString());
            foldersToRefresh.add(file.getParent());
        }
    }

    logger.debug("Balloon selection contained: " + filenames.size() + " files.");

    if (filenames.size() <= 0)
        return null;

    BalloonDialog dlg = new BalloonDialog(HandlerUtil.getActiveShell(event));
    int ret = dlg.open();
    if (ret == Window.CANCEL)
        return null;

    final int numconf = dlg.getNumConformers();

    logger.debug("User selected: " + numconf + " confomers.");

    final List<String> final_fnames = filenames;
    final List<IResource> final_foldersToRefresh = foldersToRefresh;

    //Set up a job
    Job job = new Job("Ballon 3D conformer generation") {
        protected IStatus run(IProgressMonitor monitor) {

            monitor.beginTask("Running Balloon 3D conformer generation: " + numconf + " conformers for "
                    + final_fnames + " files", 2);
            monitor.worked(1);

            //Run balloon on the files
            IBalloonManager balloon = Activator.getDefault().getJavaBalloonManager();
            List<String> ret = null;
            try {
                ret = balloon.generate3Dconformations(final_fnames, numconf);
            } catch (BioclipseException e) {
                logger.error("Balloon failed: " + e.getMessage());
                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Balloon failed: " + e.getMessage());
            }

            if (ret == null) {
                logger.error("Balloon failed: " + ret);
                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Balloon failed.");
            }
            for (String r : ret) {
                logger.debug("Balloon wrote output file: " + r);
            }

            //Refresh folders in UI thread
            Display.getDefault().syncExec(new Runnable() {
                public void run() {
                    for (IResource res : final_foldersToRefresh) {
                        try {
                            res.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
                        } catch (CoreException e) {
                            logger.error("Could not refresh resource: " + res + " - " + e.getMessage());
                        }
                    }

                }
            });

            monitor.done();

            return Status.OK_STATUS;
        }
    };
    job.setPriority(Job.LONG);
    job.setUser(true);
    job.schedule(); // start as soon as possible

    return null;
}

From source file:net.bioclipse.balloon.handlers.BalloonGen3DHandler.java

License:Open Source License

/**
 * the command has been executed, so extract extract the needed information
 * from the application context.//from   w ww.j a v a  2s. c o  m
 */
public Object execute(ExecutionEvent event) throws ExecutionException {

    ISelection sel = HandlerUtil.getCurrentSelection(event);
    if (sel == null)
        return null;
    if (!(sel instanceof StructuredSelection))
        return null;
    IStructuredSelection ssel = (IStructuredSelection) sel;

    //We operate on files and IMolecules
    List<IFile> inputFiles = new ArrayList<IFile>();
    List<IResource> foldersToRefresh = new ArrayList<IResource>();
    //Collect files
    for (Object obj : ssel.toList()) {
        if (obj instanceof IFile) {
            IFile file = (IFile) obj;
            //                filenames.add( file.getRawLocation().toOSString() );
            inputFiles.add(file);
            foldersToRefresh.add(file.getParent());
        }
    }

    logger.debug("Balloon selection contained: " + inputFiles.size() + " files.");

    if (inputFiles.size() <= 0)
        return null;

    final List<String> final_fnames = null;
    final List<IResource> final_foldersToRefresh = foldersToRefresh;

    IContentType cmlType = Platform.getContentTypeManager()
            .getContentType("net.bioclipse.contenttypes.cml.singleMolecule2d");

    IBalloonManager balloon = Activator.getDefault().getJavaBalloonManager();
    for (IFile input : inputFiles) {
        try {
            IContentDescription contentDescirpton = input.getContentDescription();
            if (contentDescirpton != null && contentDescirpton.getContentType().isKindOf(cmlType)) {
                String output = balloon.generate3Dcoordinates(input.getRawLocation().toOSString());
                Display.getDefault().syncExec(new Runnable() {
                    public void run() {
                        for (IResource res : final_foldersToRefresh) {
                            try {
                                res.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
                            } catch (CoreException e) {
                                logger.error("Could not refresh resource: " + res + " - " + e.getMessage());
                            }
                        }

                    }
                });
                ICDKManager cdk = net.bioclipse.cdk.business.Activator.getDefault().getJavaCDKManager();
                List<ICDKMolecule> molecules = cdk.loadMolecules(output);
                cdk.saveMolecule(molecules.get(0), output, true);

                return null;
            }
        } catch (Exception e) {
            LogUtils.handleException(e, logger, "net.bioclipse.balloon.business");
            return null;
        }

        balloon.generate3Dcoordinates(input, new BioclipseUIJob<IFile>() {

            @Override
            public void runInUI() {

                try {
                    IFile result = this.getReturnValue();
                    result.getParent().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
                } catch (CoreException e) {
                    LogUtils.handleException(e, logger, "net.bioclipse.balloon.business");
                }
            }
        });
    }
    //Set up a job
    Job job = new Job("Ballon 3D conformer generation") {
        protected IStatus run(IProgressMonitor monitor) {

            monitor.beginTask("Running Balloon 3D conformer generation", 2);
            monitor.worked(1);

            //Run balloon on the files
            IBalloonManager balloon = Activator.getDefault().getJavaBalloonManager();
            List<String> ret = null;
            try {
                ret = balloon.generate3Dcoordinates(final_fnames);
            } catch (BioclipseException e) {
                logger.error("Balloon failed: " + e.getMessage());
                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Balloon failed: " + e.getMessage());
            }

            if (ret == null) {
                logger.error("Balloon failed: " + ret);
                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Balloon failed.");
            }
            for (String r : ret) {
                logger.debug("Balloon wrote output file: " + r);
            }

            //Refresh folders in UI thread
            Display.getDefault().syncExec(new Runnable() {
                public void run() {
                    for (IResource res : final_foldersToRefresh) {
                        try {
                            res.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
                        } catch (CoreException e) {
                            logger.error("Could not refresh resource: " + res + " - " + e.getMessage());
                        }
                    }

                }
            });

            monitor.done();

            return Status.OK_STATUS;
        }
    };
    // job.setPriority(Job.LONG);
    // job.setUser( true );
    // job.schedule(); // start as soon as possible

    //Bring forth the ProgressView

    /*
    //Collect and serialize smiles to temp file, 
    String smilesfile="";
    String linesep=System.getProperty("line.separator");
    if (linesep==null) linesep="\n";
            
    for (Object obj : ssel.toList()){
    if ( obj instanceof IMolecule ) {
        IMolecule mol = (IMolecule) obj;
        String smilestext;
        try {
            smilestext = mol.getSMILES();
            smilesfile=smilesfile+smilestext+ linesep;
        } catch ( BioclipseException e ) {
            logger.debug("Could not get smiles from Imol: " + mol 
                         + ". Skipped in balloon: " + e.getMessage());
        }
    }
    }
            
            
            
    try {
    File tfile = File.createTempFile( "balloontemp", "smi" );
    FileWriter writer= new FileWriter(tfile);
    writer.write( smilesfile );
    writer.close();
            
    //Run balloon on this file
            
    } catch ( IOException e ) {
    e.printStackTrace();
    }
     */

    return null;

}

From source file:net.bioclipse.cdk.smartsmatching.views.SmartsMatchingView.java

License:Open Source License

private void makeActions() {

    collapseAllAction = new Action() {
        public void run() {
            viewer.collapseAll();// w  w  w  .j  a  v  a 2s.c o m
        }
    };
    collapseAllAction.setText("Collapse all");
    collapseAllAction.setToolTipText("Collapse all SMARTS");
    collapseAllAction.setImageDescriptor(Activator.getImageDecriptor("icons/collapseall.gif"));

    expandAllAction = new Action() {
        public void run() {
            viewer.expandAll();
        }
    };
    expandAllAction.setText("Expand all");
    expandAllAction.setToolTipText("Expand all SMARTS to reveal hits");
    expandAllAction.setImageDescriptor(Activator.getImageDecriptor("icons/expandall.gif"));

    runAction = new Action() {
        public void run() {
            runSmartsMatching();
        }
    };
    runAction.setText("Run matching");
    runAction.setToolTipText("Run SMARTS matching for the active aditor");
    runAction.setImageDescriptor(Activator.getImageDecriptor("icons/smallRun.gif"));

    clearAction = new Action() {
        public void run() {
            //Re-read from prefs, creates new objects
            smartsInView = SmartsMatchingPrefsHelper.getPreferences();
            viewer.setInput(smartsInView);
        }
    };
    clearAction.setText("Clear matches");
    clearAction.setToolTipText("Clear all SMARTS matches");
    clearAction.setImageDescriptor(Activator.getImageDecriptor("icons/clear_co.gif"));

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

            AddEditSmartsDialog dlg = new AddEditSmartsDialog(getSite().getShell());
            int ret = dlg.open();
            if (ret == Window.CANCEL)
                return;

            SmartsWrapper wrapper = dlg.getSmartsWrapper();

            //Add to current list
            smartsInView.add(wrapper);

            savePrefsAndUpdate();

        }
    };
    addSmartsAction.setText("Add SMARTS");
    addSmartsAction.setToolTipText("Add a SMARTS entry");
    addSmartsAction.setImageDescriptor(Activator.getImageDecriptor("icons/add_obj.gif"));

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

            if (!(viewer.getSelection() instanceof IStructuredSelection)) {
                showError("Please select one or more SMARTS to remove");
                return;
            }
            IStructuredSelection ssel = (IStructuredSelection) viewer.getSelection();

            boolean prefsChanged = false;
            for (Object obj : ssel.toList()) {
                if (obj instanceof SmartsWrapper) {
                    prefsChanged = true;
                    SmartsWrapper swToRemove = (SmartsWrapper) obj;
                    //For all lists, remove this smart
                    for (Iterator<IWorkbenchPart> it = editorSmartsMap.keySet().iterator(); it.hasNext();) {
                        IWorkbenchPart part = it.next();
                        editorSmartsMap.get(part).remove(swToRemove);
                    }
                    smartsInView.remove(swToRemove);
                }
            }

            if (prefsChanged) {
                //Write list to preferences
                SmartsMatchingPrefsHelper.setPreferences(smartsInView);
                viewer.refresh();
            }

        }
    };
    removeSmartsAction.setText("Remove SMARTS");
    removeSmartsAction.setToolTipText("Remove the selected SMARTS");
    removeSmartsAction.setImageDescriptor(Activator.getImageDecriptor("icons/delete_obj.gif"));

    showPropertiesViewAction = new Action() {
        public void run() {
            IWorkbenchPage page = getSite().getWorkbenchWindow().getActivePage();
            try {
                page.showView(IPageLayout.ID_PROP_SHEET);
            } catch (PartInitException e) {
                showError("Could not show Properties View: " + e.getMessage());
            }
        }
    };
    showPropertiesViewAction.setText("Show Properties");
    showPropertiesViewAction.setToolTipText("Show the Properties View");
    showPropertiesViewAction.setImageDescriptor(Activator.getImageDecriptor("icons/table_row_props.gif"));

}

From source file:net.bioclipse.cdk.ui.handlers.CalculateRMSDMatrixHandler.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection sel = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
    if (!sel.isEmpty() && sel instanceof IStructuredSelection) {
        IStructuredSelection ssel = (IStructuredSelection) sel;
        ICDKManager cdk = Activator.getDefault().getJavaCDKManager();
        IUIManager ui = net.bioclipse.ui.business.Activator.getDefault().getUIManager();
        List<IMolecule> molecules = new ArrayList<IMolecule>(ssel.size());
        for (Object file : ssel.toList())
            molecules.add(cdk.loadMolecule((IFile) file));
        String path = "/Virtual/rmsd.csv";
        while (ui.fileExists(path))
            path = "/Virtual/rmsd" + UUID.randomUUID() + ".csv";
        try {//from w  w w .j ava2s .c om
            String matrix = cdk.calculateRMSD(molecules, path);
            ui.open(matrix);
        } catch (BioclipseException cause) {
            throw new ExecutionException("Error while calculating RMSD matrix...", cause);
        }
    }
    return null;
}

From source file:net.bioclipse.cdk.ui.handlers.CalculateTanimotoMatrixHandler.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection sel = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
    if (!sel.isEmpty() && sel instanceof IStructuredSelection) {
        IStructuredSelection ssel = (IStructuredSelection) sel;
        ICDKManager cdk = Activator.getDefault().getJavaCDKManager();
        IUIManager ui = net.bioclipse.ui.business.Activator.getDefault().getUIManager();
        List<IMolecule> molecules = new ArrayList<IMolecule>(ssel.size());
        for (Object file : ssel.toList())
            molecules.add(cdk.loadMolecule((IFile) file));
        String path = "/Virtual/matrix.csv";
        while (ui.fileExists(path))
            path = "/Virtual/matrix" + UUID.randomUUID() + ".csv";
        try {//  w  w w . j  a v a  2  s . c om
            String matrix = cdk.calculateTanimoto(molecules, path);
            ui.open(matrix, "net.bioclipse.editors.MatrixGridEditor");
        } catch (BioclipseException cause) {
            throw new ExecutionException("Error while calculating Tanimoto matrix...", cause);
        }
    }
    return null;
}