Example usage for org.eclipse.jface.viewers TreePath getParentPath

List of usage examples for org.eclipse.jface.viewers TreePath getParentPath

Introduction

In this page you can find the example usage for org.eclipse.jface.viewers TreePath getParentPath.

Prototype

public TreePath getParentPath() 

Source Link

Document

Returns a copy of this tree path with one segment removed from the end, or null if this tree path has no segments.

Usage

From source file:com.amalto.workbench.editors.xsdeditor.TreeExpandHelper.java

License:Open Source License

private TreePath[] removeInvalidTreePaths(TreePath[] expandedElementPaths) {
    Map<Integer, Set<TreePath>> pathMaps = new HashMap<Integer, Set<TreePath>>();
    int maxSegmentCount = -1;
    for (TreePath path : expandedElementPaths) {
        int segmentCount = path.getSegmentCount();

        Set<TreePath> pathSet = pathMaps.get(segmentCount);
        if (pathSet == null) {
            pathSet = new HashSet<TreePath>();
            pathMaps.put(segmentCount, pathSet);
        }/*from  w w w. j  a  v a  2  s. co  m*/

        pathSet.add(path);

        //
        if (maxSegmentCount < segmentCount) {
            maxSegmentCount = segmentCount;
        }
    }

    Set<TreePath> roots = pathMaps.get(1);
    if (roots == null || roots.size() == 0) {
        return new TreePath[0];
    }

    // record TreePath by tree level
    List<TreePath> paths = new ArrayList<TreePath>();
    paths.addAll(roots);

    for (int i = 2; i < maxSegmentCount + 1; i++) {
        Set<TreePath> set = pathMaps.get(i);
        if (set == null || set.size() == 0) {
            break;
        }

        Set<TreePath> parents = pathMaps.get(i - 1);
        Iterator<TreePath> iterator = set.iterator();
        while (iterator.hasNext()) {
            TreePath path = iterator.next();
            if (parents.contains(path.getParentPath())) {
                paths.add(path);
            } else {
                iterator.remove();
            }
        }
    }

    return paths.toArray(new TreePath[0]);
}

From source file:com.mercatis.lighthouse3.ui.environment.handlers.PropertyTester.java

License:Apache License

public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
    if (receiver instanceof TreeSelection) {
        TreeSelection selection = (TreeSelection) receiver;
        boolean expected = (Boolean) expectedValue;
        for (Object o : args) {
            PARAMETER p;//from   ww  w.  j av  a2  s .c  o m
            try {
                p = PARAMETER.valueOf((String) o);
            } catch (Exception e) {
                System.err.println("Argument " + o + " is not supported.\nAvailable args are:");
                for (PARAMETER pa : PARAMETER.values()) {
                    System.err.println(pa);
                }
                return false;
            }

            switch (p) {
            case multiple:
                return (selection.size() > 1) == expected;
            case deployment:
                if (selection.size() == 1) {
                    TreePath path = selection.getPaths()[0];
                    if (path != null && path.getParentPath() != null) {
                        return (path.getParentPath().getLastSegment() instanceof Location) == expected;
                    }
                }
                break;
            case project_open:
                for (TreePath path : selection.getPaths()) {
                    if (path.getFirstSegment() instanceof LighthouseDomain) {
                        LighthouseDomain lighthouseDomain = (LighthouseDomain) path.getFirstSegment();
                        return lighthouseDomain.getProject().isOpen() == expected;
                    }
                }
                break;
            default:
                return false;
            }
        }
    }
    return false;
}

From source file:com.mercatis.lighthouse3.ui.environment.handlers.RemoveDeploymentHandler.java

License:Apache License

public Object execute(ExecutionEvent event) throws ExecutionException {
    preExecution(event);//from  w w w  .  j  a  va  2s.c  o  m

    boolean selectedDeploymentPartOfStatus = false;
    ISelection selection = HandlerUtil.getCurrentSelection(event);
    if (selection instanceof TreeSelection) {
        ITreeSelection treeSelection = (ITreeSelection) selection;
        List<TreePath> paths = new ArrayList<TreePath>(Arrays.asList(treeSelection.getPaths()));

        // remove all paths that do not end in a deployment..
        for (Iterator<TreePath> it = paths.iterator(); it.hasNext();) {
            if (!(it.next().getLastSegment() instanceof Deployment)) {
                it.remove();
            }
        }

        // remove all paths where the selected deployment is part of a status..
        for (Iterator<TreePath> it = paths.iterator(); it.hasNext();) {
            TreePath path = it.next();
            Deployment deployment = (Deployment) path.getLastSegment();
            path = path.getParentPath();
            while (path != null) {
                Object element = path.getLastSegment();
                if (element instanceof StatusCarrier) {
                    StatusCarrier carrier = (StatusCarrier) element;
                    StatusRegistry registry = RegistryFactoryServiceUtil.getRegistryFactoryService(
                            StatusRegistryFactoryService.class, deployment.getLighthouseDomain(), this);
                    List<Status> statuus = registry.getStatusForCarrier(carrier);
                    for (Status status : statuus) {
                        if (contextContainsDeployment(status.getOkTemplate(), deployment)) {
                            selectedDeploymentPartOfStatus = true;
                            it.remove();
                            break;
                        }

                        if (contextContainsDeployment(status.getErrorTemplate(), deployment)) {
                            selectedDeploymentPartOfStatus = true;
                            it.remove();
                            break;
                        }
                    }
                }
                path = path.getParentPath();
            }
        }

        // detach remaining deployments..
        for (Iterator<TreePath> it = paths.iterator(); it.hasNext();) {
            TreePath path = it.next();
            Deployment deployment = (Deployment) path.getLastSegment();
            DeploymentCarryingDomainModelEntity<?> carrier = (DeploymentCarryingDomainModelEntity<?>) path
                    .getParentPath().getLastSegment();
            carrier.detachDeployment(deployment);

            if (carrier instanceof Environment) {
                EnvironmentRegistry registry = RegistryFactoryServiceUtil.getRegistryFactoryService(
                        EnvironmentRegistryFactoryService.class, carrier.getLighthouseDomain(), this);
                registry.update((Environment) carrier);
            }
            if (carrier instanceof ProcessTask) {
                ProcessTaskRegistry registry = RegistryFactoryServiceUtil.getRegistryFactoryService(
                        ProcessTaskRegistryFactoryService.class, carrier.getLighthouseDomain(), this);
                registry.update((ProcessTask) carrier);
            }
            containers.add(domainService.getLighthouseDomainByEntity(carrier).getContainerFor(carrier));
        }

        // notify user on deployments that were not detached..
        if (selectedDeploymentPartOfStatus) {
            Shell shell = HandlerUtil.getActiveShell(event);
            MessageDialog.openWarning(shell, "Deployments not detached",
                    "One or more deployments were not detached because they are part of a status.");
        }
    }

    postExecution(event);
    return null;
}

From source file:de.walware.statet.r.internal.objectbrowser.DeleteHandler.java

License:Open Source License

@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
    if (!UIAccess.isOkToUse(this.view.getViewer())) {
        return null;
    }/*from   w w  w  . ja v a2s .c om*/
    final ITreeSelection selection = this.view.getSelection();
    if (!isValidSelection(selection)) {
        return null;
    }
    final TreePath[] treePaths = selection.getPaths();
    Arrays.sort(treePaths, new Comparator<TreePath>() {
        @Override
        public int compare(final TreePath o1, final TreePath o2) {
            return o1.getSegmentCount() - o2.getSegmentCount();
        }
    });
    final IElementComparer comparer = new IElementComparer() {
        @Override
        public int hashCode(final Object e) {
            return e.hashCode();
        }

        @Override
        public boolean equals(final Object e1, final Object e2) {
            return (e1 == e2);
        }
    };
    final List<String> commands = new ArrayList<String>(treePaths.length);
    final List<String> names = new ArrayList<String>(treePaths.length);
    final Set<IElementName> topEnvirs = new HashSet<IElementName>(treePaths.length);
    ITER_ELEMENTS: for (int i = 0; i < treePaths.length; i++) {
        for (int j = 0; j < i; j++) {
            if (treePaths[j] != null && treePaths[i].startsWith(treePaths[j], comparer)) {
                treePaths[i] = null;
                continue ITER_ELEMENTS;
            }
        }

        final TreePath treePath = treePaths[i];
        final ICombinedRElement element = ContentProvider.getCombinedRElement(treePath.getLastSegment());
        final ICombinedRElement parent = element.getModelParent();

        final RElementName elementName = this.view.getElementName(treePath);
        if (parent != null && elementName != null) {
            final RElementName topName;
            switch (parent.getRObjectType()) {
            case RObject.TYPE_ENV: {
                final RElementName envirName = (treePath.getSegmentCount() > 1)
                        ? this.view.getElementName(treePath.getParentPath())
                        : parent.getElementName();
                final IElementName itemName = element.getElementName();
                topName = elementName.getNamespace();
                if (envirName != null) { // elementName ok => segmentName ok
                    commands.add("rm(`" + itemName.getSegmentName() + "`," + //$NON-NLS-1$ //$NON-NLS-2$ 
                            "pos=" + RElementName.createDisplayName(envirName, //$NON-NLS-1$
                                    RElementName.DISPLAY_NS_PREFIX | RElementName.DISPLAY_EXACT)
                            + ")");
                    names.add(elementName.getDisplayName());
                    topEnvirs.add(topName);
                    continue ITER_ELEMENTS;
                }
                break;
            }
            case RObject.TYPE_LIST:
            case RObject.TYPE_DATAFRAME:
            case RObject.TYPE_S4OBJECT:
                topName = elementName.getNamespace();
                final String name = RElementName.createDisplayName(elementName, RElementName.DISPLAY_EXACT);
                commands.add("with(" + RElementName.createDisplayName(topName, RElementName.DISPLAY_NS_PREFIX) //$NON-NLS-1$
                        + "," + //$NON-NLS-1$ 
                        name + "<-NULL" + //$NON-NLS-1$
                        ")"); //$NON-NLS-1$
                names.add(elementName.getDisplayName());
                topEnvirs.add(topName);
                continue ITER_ELEMENTS;
            }
        }

        final StringBuilder message = new StringBuilder("Selection contains unsupported object");
        if (elementName != null) {
            message.append("\n\t"); //$NON-NLS-1$
            message.append(elementName.getDisplayName());
        } else {
            message.append("."); //$NON-NLS-1$
        }
        MessageDialog.openError(this.view.getSite().getShell(), "Delete", message.toString());
        return null;
    }

    final StringBuilder message = new StringBuilder(
            names.size() == 1 ? "Are you sure you want to delete the object"
                    : NLS.bind("Are you sure you want to delete these {0} objects:", names.size()));
    final int show = (names.size() > 5) ? 3 : names.size();
    for (int i = 0; i < show; i++) {
        message.append("\n\t"); //$NON-NLS-1$
        message.append(names.get(i));
    }
    if (show < names.size()) {
        message.append("\n\t..."); //$NON-NLS-1$
    }

    final ToolProcess process = this.view.getTool();
    if (ToolMessageDialog.openConfirm(process, this.view.getSite().getShell(), "Delete", message.toString())) {
        process.getQueue().add(new DeleteRunnable(names, commands, topEnvirs));
    }

    return null;
}

From source file:es.cv.gvcase.fefem.common.composites.EMFContainedHierarchicalCollectionEditionComposite.java

License:Open Source License

/**
 * Creates the a SelectionListener which will invoke the code to remove/delete
 * a selected element from the tree viewer.
 *     /*w  ww .j a v a  2  s  .  c  om*/
 * @return SelectionListener the {@link SelectionListener} which will
 * remove/delete a selected element from the viewer.  
 */
protected SelectionListener getRemoveButtonSelectionListener() {
    SelectionAdapter adapter = new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {

            TreeViewer viewer = getViewer();
            if (viewer.getSelection() instanceof TreeSelection) {
                TreeSelection selection = (TreeSelection) viewer.getSelection();
                List<?> elementsToDelete = selection.toList();
                if (elementsToDelete.size() > 0) {
                    // We prepare the next selection, based on the element to delete
                    EObject eObject = (EObject) elementsToDelete.get(0);
                    TreePath path = selection.getPathsFor(eObject)[0];
                    TreeSelection nextSelection = TreeSelection.EMPTY;
                    ;
                    if (path.getSegmentCount() == 1) { // If it is a first level element, we will select a sibling element
                        if (modelObservable.size() > 1) { // If we have more than one element 
                            int pos = modelObservable.indexOf(eObject);
                            nextSelection = (pos == modelObservable.size() - 1) // If it's the last first level element, we will select the previous sibling
                                    ? new TreeSelection(
                                            new TreePath(new Object[] { modelObservable.get(pos - 1) }))
                                    : new TreeSelection(
                                            new TreePath(new Object[] { modelObservable.get(pos + 1) })); // otherwise, we will select the next one
                        }
                    } else { // If it is not a first level element, we will select its parent element
                        nextSelection = new TreeSelection(path.getParentPath());
                    }

                    EditingDomain domain = getEditingDomain();
                    domain.getCommandStack().execute(DeleteCommand.create(domain, elementsToDelete));
                    getPage().setDirty(true);
                    viewer.setSelection(nextSelection);
                }
            }
        }
    };
    return adapter;
}

From source file:nexcore.tool.uml.ui.project.explorer.action.BaseMultiFragmentAction.java

License:Open Source License

/**
 * hierarchyCheck//from www  .  j a  v a  2s  .c  o  m
 *  
 * @return boolean
 */
protected boolean hierarchyCheck() {
    CommonViewer commonViewer = ViewerRegistry.getViewer();
    TreeSelection sel = (TreeSelection) commonViewer.getSelection();

    List<TreePath> pathList = Arrays.asList(sel.getPaths());

    for (TreePath path : pathList) {
        if (isContains(pathList, path.getParentPath())) {
            MessageDialog.openError(ProjectExplorerPlugin.getShell(), UMLMessage.LABEL_FILE_FRAGMENTATION,
                    UMLMessage.MESSAGE_FRAGMENT_DEFRAGMENT_ERROR_MESSAGE/*"  ?  ??  ? /?   ."*/);
            return false;
        }
    }

    return true;
}

From source file:nexcore.tool.uml.ui.project.explorer.action.BaseMultiFragmentAction.java

License:Open Source License

/**
 * ? ? parent - child   ? ?/*from  w  w  w  .  jav a 2  s.c o m*/
 * 
 * 
 * @param pathList
 * @param treePath
 * @return boolean
 */
protected boolean isContains(List<TreePath> pathList, TreePath treePath) {
    if (treePath == null) {
        return false;
    }
    if (pathList.contains(treePath)) {
        return true;
    } else {
        if (treePath.getParentPath() != null) {
            return isContains(pathList, treePath.getParentPath());
        }
    }
    return false;
}

From source file:objectview.EObjectFocusDomain.java

License:Open Source License

/**
 * Returns the longest tree path, which is actually shown in the UI. 
 * /*from   ww  w.j a v  a  2 s.co  m*/
 * E.g. We may seek to show a property of a Bit, forming a path of
 * crml/repository/key/bit/property. If we failed to show the property, 
 * the last element in the tree path is the Bit. In case, we could 
 * only show the bit mask key, the returned path is (crml/repository/key). 
 */
public TreePath canFocusUpTo(TreePath path) {
    try {
        TreePath canShow = null;
        for (IObjectView objectView : getViews()) {
            TreePath tryShow = path;
            while (tryShow != null) {
                if (objectView.canShow(tryShow.getLastSegment())) {
                    if (canShow == null || tryShow.getSegmentCount() > canShow.getSegmentCount()) {
                        canShow = tryShow;
                    }
                    break;
                }
                tryShow = tryShow.getParentPath();
            }
        }
        return canShow;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:objectview.EObjectFocusDomain.java

License:Open Source License

/**
 * Try to display the item of tree path in views in the greatest 
 * accuracy possible. Returns longest tree path, which is actually 
 * shown in the UI. /*w ww .  java 2s .  c  o m*/
 */
public TreePath focus(TreePath path, boolean tryActivate) {
    try {
        TreeSelection newFocus = new TreeSelection(path);
        if (tryActivate || !newFocus.equals(focus)) {
            focus = newFocus;
            TreePath shown = null;
            for (IObjectView objectView : getViews()) {
                TreePath tryShow = path;
                while (tryShow != null) {
                    if (objectView.canShow(tryShow.getLastSegment())) {
                        objectView.show(tryShow.getLastSegment(), tryActivate);
                        if (shown == null || tryShow.getSegmentCount() > shown.getSegmentCount()) {
                            shown = tryShow;
                        }
                        break;
                    }
                    tryShow = tryShow.getParentPath();
                }
            }
            // Fire selection changed 
            for (ISelectionChangedListener l : listeners) {
                l.selectionChanged(new SelectionChangedEvent(this, focus));
            }
            return shown;
        } else {
            return canFocusUpTo(path);
        }
    } catch (Exception e) {
        //e.printStackTrace();
        //throw new RuntimeException(e); 
        return null;
    }
}

From source file:org.eclipe.debug.tests.viewer.model.SelectionTests.java

License:Open Source License

/**
 * In this test:/*from w w w  .  j av  a 2  s  . co  m*/
 * - set a seleciton to an element 
 * - then remove that element 
 * - update the view with remove delta
 * -> The selection should be re-set to empty.
 */
public void testSelectRemove() throws InterruptedException {
    //TreeModelViewerAutopopulateAgent autopopulateAgent = new TreeModelViewerAutopopulateAgent(fViewer);

    // Create the model and populate the view.
    TestModel model = makeMultiLevelModel();

    // Create a selection object to the deepest part of the tree.
    TreePath elementPath = model.findElement("3.3.3");
    TreeSelection selection = new TreeSelection(elementPath);

    // Set the selection.
    fViewer.setSelection(selection, true, false);

    // Remove the element
    TreePath removePath = model.findElement("3");
    TreePath parentPath = removePath.getParentPath();
    int removeIndex = model.getElement(parentPath).indexOf(model.getElement(removePath));
    ModelDelta delta = model.removeElementChild(removePath.getParentPath(), removeIndex);

    // Configure a selection listener
    SelectionListener listener = new SelectionListener();
    fViewer.addSelectionChangedListener(listener);

    // Reset the listener and update the viewer.  With a remove
    // delta only wait for the delta to be processed.
    fListener.reset();
    model.postDelta(delta);
    while (!fListener.isFinished(ITestModelUpdatesListenerConstants.MODEL_CHANGED_COMPLETE))
        if (!fDisplay.readAndDispatch())
            Thread.sleep(0);

    // Check to make sure the selection was made
    //assertTrue(listener.fEvents.size() == 1);

    // Check that the new selection is empty
    ISelection viewerSelection = fViewer.getSelection();
    assertTrue(viewerSelection.isEmpty());
}