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

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

Introduction

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

Prototype

public Object[] toArray();

Source Link

Document

Returns the elements in this selection as an array.

Usage

From source file:net.tourbook.importdata.RawDataManager.java

License:Open Source License

/**
 * @param reimportId// ww  w  .  j av  a2 s .com
 *            ID how a tour is reimported.
 * @param tourViewer
 *            Tour viewer where the selected tours should be reimported.
 */
public void actionReimportTour(final ReImport reimportId, final ITourViewer3 tourViewer) {

    final long start = System.currentTimeMillis();

    // check if the tour editor contains a modified tour
    if (TourManager.isTourEditorModified()) {
        return;
    }

    if (actionReimportTour_10_Confirm(reimportId) == false) {
        return;
    }

    // prevent async error in the save tour method, cleanup environment
    tourViewer.getPostSelectionProvider().clearSelection();

    Util.clearSelection();

    TourManager.fireEvent(TourEventId.CLEAR_DISPLAYED_TOUR, null, null);

    // get selected tours
    final IStructuredSelection selectedTours = ((IStructuredSelection) tourViewer.getViewer().getSelection());

    setImportId();
    setImportCanceled(false);

    final IRunnableWithProgress importRunnable = new IRunnableWithProgress() {

        @Override
        public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {

            boolean isReImported = false;
            File reimportedFile = null;
            int imported = 0;
            final int importSize = selectedTours.size();

            monitor.beginTask(Messages.Import_Data_Dialog_Reimport_Task, importSize);

            // loop: all selected tours in the viewer
            for (final Object element : selectedTours.toArray()) {

                if (monitor.isCanceled()) {
                    // stop reimporting but process reimported tours
                    break;
                }

                monitor.worked(1);
                monitor.subTask(NLS.bind(Messages.Import_Data_Dialog_Reimport_SubTask, //
                        new Object[] { ++imported, importSize }));

                TourData oldTourData = null;

                if (element instanceof TVITourBookTour) {
                    oldTourData = TourManager.getInstance()
                            .getTourData(((TVITourBookTour) element).getTourId());
                } else if (element instanceof TourData) {
                    oldTourData = (TourData) element;
                }

                if (oldTourData == null) {
                    continue;
                }

                boolean isTourReImportedFromSameFile = false;

                if (reimportedFile != null && _newlyImportedTours.size() > 0) {

                    // this case occures when a file contains multiple tours

                    if (actionReimportTour_30(reimportId, reimportedFile, oldTourData)) {
                        isReImported = true;
                        isTourReImportedFromSameFile = true;
                    }
                }

                if (isTourReImportedFromSameFile == false) {

                    reimportedFile = actionReimportTour_20_GetImportFile(oldTourData);

                    if (reimportedFile == null) {
                        // user canceled file dialog
                        break;
                    }

                    // import file is available

                    if (actionReimportTour_30(reimportId, reimportedFile, oldTourData)) {
                        isReImported = true;
                    }
                }
            }

            if (isReImported) {

                updateTourData_InImportView_FromDb(monitor);

                // reselect tours, run in UI thread
                Display.getDefault().asyncExec(new Runnable() {
                    @Override
                    public void run() {
                        tourViewer.reloadViewer();
                        tourViewer.getViewer().setSelection(selectedTours, true);
                    }
                });
            }
        }
    };

    try {
        new ProgressMonitorDialog(Display.getDefault().getActiveShell()).run(true, true, importRunnable);
    } catch (final Exception e) {
        TourLogManager.logEx(e);
    } finally {

        final double time = (System.currentTimeMillis() - start) / 1000.0;
        TourLogManager.addLog(//
                TourLogState.DEFAULT, String.format(RawDataManager.LOG_REIMPORT_END, time));

    }
}

From source file:net.tourbook.ui.views.rawData.RawDataView.java

License:Open Source License

/**
 * Remove all tours from the raw data view which are selected
 *//*w w  w . j  av  a  2 s  .  c  om*/
void actionRemoveTour() {

    final IStructuredSelection selection = ((IStructuredSelection) _tourViewer.getSelection());
    if (selection.size() == 0) {
        return;
    }

    /*
     * convert selection to array
     */
    final Object[] selectedItems = selection.toArray();
    final TourData[] selectedTours = new TourData[selection.size()];
    for (int i = 0; i < selectedItems.length; i++) {
        selectedTours[i] = (TourData) selectedItems[i];
    }

    _rawDataMgr.removeTours(selectedTours);

    _postSelectionProvider.clearSelection();

    TourManager.fireEvent(TourEventId.CLEAR_DISPLAYED_TOUR, null, RawDataView.this);

    // update the table viewer
    reloadViewer();
}

From source file:no.resheim.eclipse.quicklook.macosx.handlers.QuickLookHandler.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection currentSelection = HandlerUtil.getCurrentSelection(event);
    if (currentSelection != null) {
        if (currentSelection instanceof IStructuredSelection) {
            IStructuredSelection s = (IStructuredSelection) currentSelection;
            ArrayList<String> paths = new ArrayList<String>();
            Object[] objects = s.toArray();
            for (Object object : objects) {
                if (object instanceof IAdaptable) {
                    Object adapter = ((IAdaptable) object).getAdapter(IResource.class);
                    if (adapter != null) {
                        String osString = ((IResource) adapter).getLocation().toOSString();
                        paths.add(osString);
                    }//from  ww w . ja va  2  s . c o m
                }
            }
            if (paths.size() > 0) {
                try {
                    execute(paths.toArray(new String[paths.size()]));
                } catch (Exception e) {
                    IStatus status = new Status(IStatus.ERROR, "no.resheim.eclipse.utils.quicklook.macosx", //$NON-NLS-1$
                            "Could not execute QuickLookHandler", e); //$NON-NLS-1$
                    StatusManager.getManager().handle(status);
                }
            }
        }
    }
    return null;
}

From source file:org.absmodels.abs.plugin.wizards.NewABSFileWizard.java

License:Open Source License

/**
 * @param selection//  w  ww  .j  ava2 s .  co m
 * @return The first ModulePath element in the given selection, or null if
 *         the selection is null or the selection does not contain any
 *         ModulePath element
 */
private ModulePath getLastModulePathElement(IStructuredSelection selection) {
    if (selection != null) {
        Object[] array = selection.toArray();
        for (int i = array.length - 1; i >= 0; i--) {
            Object o = array[i];
            if (o instanceof ModulePath) {
                ModulePath mp = (ModulePath) o;
                return mp;
            }
        }
    }

    return null;
}

From source file:org.adorsys.plh.pkix.workbench.navigator.internal.ResourceNavigator.java

License:Open Source License

@Inject
public ResourceNavigator(Composite parent, final IEclipseContext context, IWorkspace workspace) {
    final Realm realm = SWTObservables.getRealm(parent.getDisplay());
    this.context = context;
    parent.setLayout(new FillLayout());
    TreeViewer viewer = new TreeViewer(parent, SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
    viewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            StructuredSelection selection = (StructuredSelection) event.getSelection();
            selectionService// w  w w  . ja va  2s. c o  m
                    .setSelection(selection.size() == 1 ? selection.getFirstElement() : selection.toArray());
            //            context.modify(IServiceConstants.ACTIVE_SELECTION, selection.size() == 1 ? selection.getFirstElement() : selection.toArray());
        }
    });

    IObservableFactory setFactory = new IObservableFactory() {
        public IObservable createObservable(Object element) {
            if (element instanceof IContainer && ((IContainer) element).exists()) {
                IObservableSet observableSet = observableSets.get(element);
                if (observableSet == null) {
                    observableSet = new WritableSet(realm);
                    try {
                        observableSet.addAll(Arrays.asList(((IContainer) element).members()));
                    } catch (CoreException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    observableSets.put((IContainer) element, observableSet);
                }
                return observableSet;
            }
            return Observables.emptyObservableSet();
        }
    };
    viewer.setContentProvider(new ObservableSetTreeContentProvider(setFactory, new TreeStructureAdvisor() {
        public Boolean hasChildren(Object element) {
            return Boolean.valueOf(element instanceof IContainer);
        }
    }));

    viewer.setLabelProvider(new LabelProvider() {
        public String getText(Object element) {
            if (element instanceof IResource)
                return ((IResource) element).getName();
            return element == null ? "" : element.toString();
        }
    });
    viewer.setSorter(new ViewerSorter());
    viewer.setInput(workspace.getRoot());
    viewer.addOpenListener(new IOpenListener() {

        public void open(OpenEvent event) {
            IStructuredSelection s = (IStructuredSelection) event.getSelection();
            for (Object o : s.toArray()) {
                if (o instanceof IFile) {
                    IFile f = (IFile) o;
                    context.set(IFile.class, f);
                    String fExt = f.getFileExtension();
                    EDITOR: for (MPartDescriptor desc : application.getDescriptors()) {
                        String category = desc.getCategory();
                        if (category == null)
                            continue;
                        String[] categories = category.split(",");
                        for (String ext : categories) {
                            if (ext.equalsIgnoreCase(fExt)) {
                                context.set(MPartDescriptor.class, desc);
                                System.err.println("Opening with: " + desc);
                                Command cmd = commandService.getCommand("desktop.command.openeditor");
                                ParameterizedCommand pCmd = ParameterizedCommand.generateCommand(cmd, null);
                                handlerService.executeHandler(pCmd);

                                break EDITOR;
                            }
                        }
                    }
                }
            }

        }
    });
    setupContextMenu(viewer, parent.getShell());
    workspace.addResourceChangeListener(listener);
}

From source file:org.amanzi.awe.render.core.utils.RenderMenuUtils.java

License:Open Source License

public static Pair<IRenderableModel, Iterable<IDataElement>> getLocationElements(
        final IStructuredSelection selection) {
    IRenderableModel renderableModel = null;
    boolean incorrect = false;

    Iterable<IDataElement> elementsIterable = Iterables.emptyIterable();

    for (final Object element : selection.toArray()) {
        if (element instanceof IUIItem) {
            final IUIItem item = (IUIItem) element;

            final IRenderableModel itemModel = getRenderableModel(item);

            // check UI Item is correct
            if (itemModel == null) {
                incorrect = true;/*ww w. j a  v  a  2 s .  co  m*/
                break;
            }

            // check model is same for all elements
            if (renderableModel == null) {
                renderableModel = itemModel;
            } else if (!itemModel.equals(renderableModel)) {
                incorrect = true;
                break;
            }

            // check internal elements
            final Iterable<IDataElement> subIterable = collectDataElements(item, renderableModel);

            if (subIterable != null) {
                elementsIterable = Iterables.concat(elementsIterable, subIterable);
            }

        }
    }

    // check element locations
    if (!incorrect && !Iterables.isEmpty(elementsIterable)) {
        incorrect = Iterables.isEmpty(renderableModel.getElementsLocations(elementsIterable));
    }

    if (!incorrect) {
        return new ImmutablePair<IRenderableModel, Iterable<IDataElement>>(renderableModel, elementsIterable);
    }

    return null;
}

From source file:org.apache.directory.studio.ldapbrowser.common.actions.BrowserSelectionUtils.java

License:Apache License

/**
 * Gets all beans of the requested type contained in the given selection.
 *
 * @param selection the selection/*from   w  w  w .  j  ava2s.co  m*/
 * @param type the requested type
 * @return a list containing beans of the requested type
 */
private static List<Object> getTypes(ISelection selection, Class<?> type) {
    List<Object> list = new ArrayList<Object>();

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

        for (Object element : structuredSelection.toArray()) {
            if (type.isInstance(element)) {
                list.add(element);
            }
        }
    }

    return list;
}

From source file:org.apache.felix.sigil.eclipse.ui.internal.editors.project.ClasspathSection.java

License:Apache License

@SuppressWarnings("unchecked")
private void handleRemoved() {
    IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();

    if (!selection.isEmpty()) {
        for (Iterator<IClasspathEntry> i = selection.iterator(); i.hasNext();) {
            getBundle().removeClasspathEntry(
                    getProjectModel().getJavaModel().encodeClasspathEntry(i.next()).trim());
        }/* w ww  .  j a  v a2s .co m*/
        viewer.remove(selection.toArray());
        markDirty();
    }
}

From source file:org.apache.felix.sigil.eclipse.ui.internal.editors.project.PackageContentsSection.java

License:Apache License

@SuppressWarnings("unchecked")
private void handleRemoved() {
    IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();

    if (!selection.isEmpty()) {
        for (Iterator<String> i = selection.iterator(); i.hasNext();) {
            getBundle().removePackage(i.next());
        }/*from   w  ww . ja v a  2s .c o m*/
        viewer.remove(selection.toArray());
        markDirty();
    }
}

From source file:org.apache.felix.sigil.eclipse.ui.internal.preferences.ExcludedResourcesPrefsPage.java

License:Apache License

@Override
protected Control createContents(Composite parent) {
    // Create controls
    Composite composite = new Composite(parent, SWT.NONE);
    Table table = new Table(composite, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);

    Button btnAdd = new Button(composite, SWT.PUSH);
    btnAdd.setText("Add");

    final Button btnRemove = new Button(composite, SWT.PUSH);
    btnRemove.setText("Remove");
    btnRemove.setEnabled(false);/*from w  ww .j  a  va 2 s  .  com*/

    // Create viewer
    viewer = new TableViewer(table);
    viewer.setContentProvider(new ArrayContentProvider());

    // Load data
    loadPreferences(false);
    viewer.setInput(resources);

    // Listeners
    viewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            btnRemove.setEnabled(!viewer.getSelection().isEmpty());
        }
    });

    btnRemove.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
            Object[] deleted = selection.toArray();
            for (Object delete : deleted) {
                resources.remove(delete);
            }
            viewer.remove(deleted);
        }
    });

    btnAdd.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            InputDialog dialog = new InputDialog(getShell(), "Add Resource", "Enter resource name", "",
                    new IInputValidator() {
                        public String isValid(String newText) {
                            String error = null;
                            if (newText == null || newText.length() == 0) {
                                error = "Name must not be empty.";
                            } else if (resources.contains(newText)) {
                                error = "Specified resource name is already on the list.";
                            }
                            return error;
                        }
                    });

            if (dialog.open() == Window.OK) {
                String value = dialog.getValue();
                resources.add(value);
                viewer.add(value);
            }
        }
    });

    // Layout
    composite.setLayout(new GridLayout(2, false));
    table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 3));
    btnAdd.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
    btnRemove.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));

    return composite;
}