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

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

Introduction

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

Prototype

public int size();

Source Link

Document

Returns the number of elements selected in this selection.

Usage

From source file:com.nokia.tools.s60.editor.actions.AbstractAction.java

License:Open Source License

@Override
public void run() {

    selection = new StructuredSelection(
            ((IStructuredSelection) getSelectionProvider().getSelection()).toArray());

    /* fix for selection for TreeNode's */
    selection = preprocessSelection(selection);

    final IStructuredSelection sel = (IStructuredSelection) getSelection();
    if (!multipleSelection && sel.size() == 1) {
        doRun(sel.getFirstElement());/*w w w.j a v  a 2  s .  c o m*/
    } else if (multipleSelection && sel.size() > 0) {
        Iterator it = sel.iterator();
        List<Object> elements = new ArrayList<Object>();
        while (it.hasNext())
            elements.add(it.next());
        if (this instanceof AbstractMultipleSelectionAction) {
            ((AbstractMultipleSelectionAction) this).doRun(elements);
        } else {
            doRun(elements);
        }

    }
}

From source file:com.nokia.tools.s60.editor.actions.AbstractAction.java

License:Open Source License

/**
 * replaces items in selection, so that there are object user friendly for
 * later processing, i.e. replaces TreeNode's with it's data object.
 * /*  w w  w.  ja  v  a2  s .c om*/
 * @param s
 * @return
 */
private IStructuredSelection preprocessSelection(IStructuredSelection s) {
    if (s != null && s.size() > 0) {
        List<Object> tmp = new ArrayList<Object>();
        Iterator it = s.iterator();
        while (it.hasNext()) {
            Object obj = it.next();

            if (obj.getClass().getName().indexOf("TreeNode") > 0) {
                try {
                    Object data = obj.getClass().getMethod("getContent", (Class[]) null).invoke(obj,
                            (Object[]) null);
                    if (data instanceof IContentData) {

                        Set childrens = (Set) obj.getClass().getMethod("getChildren", (Class[]) null)
                                .invoke(obj, (Object[]) null);
                        if (childrens.size() == 1) {
                            data = childrens.toArray()[0];
                            data = data.getClass().getMethod("getContent", (Class[]) null).invoke(data,
                                    (Object[]) null);
                            if (data instanceof IScreenElement)
                                obj = ((IScreenElement) data).getData();
                        }
                    } else if (data instanceof IScreenElement) {
                        obj = ((IScreenElement) data).getData();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            tmp.add(obj);
        }
        return new StructuredSelection(tmp);
    }
    return s;
}

From source file:com.nokia.tools.s60.editor.actions.AbstractAction.java

License:Open Source License

@Override
protected boolean calculateEnabled() {
    layerCache.enable();/*from  www .  j a  va 2s  .c  o  m*/
    try {
        if (getSelectionProvider() == null) {
            return false;
        }
        if (!(getSelectionProvider().getSelection() instanceof IStructuredSelection))
            return false;

        // store original selection
        selection = (IStructuredSelection) getSelectionProvider().getSelection();

        selection = preprocessSelection(selection);

        final IStructuredSelection sel = (IStructuredSelection) getSelection();
        if (sel.size() == 1) {
            return doCalculateEnabled(sel.getFirstElement(), 0);
        } else if (multipleSelection && sel.size() > 1) {
            Iterator it = sel.iterator();
            int index = 0;
            while (it.hasNext()) {
                Object next = it.next();
                if (next != null) {
                    boolean enabled = doCalculateEnabled(next, index++);
                    if (!enabled && multipleSelectionEnablement == MultipleSelectionEnablementEnum.ALL) {
                        return false;
                    } else if (enabled && multipleSelectionEnablement == MultipleSelectionEnablementEnum.ONE) {
                        return true;
                    }
                }
            }
            if (multipleSelectionEnablement == MultipleSelectionEnablementEnum.ONE) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    } finally {
        layerCache.disable();
    }
}

From source file:com.nokia.tools.s60.editor.actions.ClearImageEditorAction.java

License:Open Source License

public void run() {

    IStructuredSelection selection = this.selection;

    boolean multi = false;
    List<Command> multiCmdList = null;
    if (selection.size() > 1) {
        multi = true;//from w w w  .  j  a  va  2  s.  co m
        multiCmdList = new ArrayList<Command>();
    }

    IContentData data = null;
    EditPart editPart = null;
    // partEntity - for 9-piece elements
    IImage partEntity = null;

    Iterator els = selection.iterator();
    while (els.hasNext()) {

        Object obj = els.next();

        if (obj instanceof IContentData) {
            data = (IContentData) obj;
        } else if (obj instanceof EditPart) {
            IScreenElement screenElement = getScreenElement((EditPart) obj);
            if (screenElement == null) {
                continue;
            }
            data = screenElement.getData();
        } else {
            boolean isPartElement = false;

            if (obj instanceof Object[]) {
                IImage selectedImg = null;
                if (((Object[]) obj)[1] instanceof IImage)
                    selectedImg = (IImage) ((Object[]) obj)[1];
                else if (((Object[]) obj)[1] instanceof ILayer) {
                    selectedImg = ((ILayer) ((Object[]) obj)[1]).getParent();
                }
                if (selectedImg != null) {
                    // EditPart or IContentData is in selection

                    if (selectedImg.isPart()) {
                        isPartElement = true;
                        partEntity = selectedImg;
                    }

                    if (((Object[]) obj)[2] instanceof EditPart) {
                        editPart = (EditPart) ((Object[]) obj)[2];
                        IScreenElement screenElement = getScreenElement(editPart);
                        data = screenElement.getData();
                    } else if (((Object[]) obj)[2] instanceof IContentData) {
                        editPart = null;
                        data = (IContentData) ((Object[]) obj)[2];
                    }
                }
            }
            if (isPartElement && partEntity == null) {
                continue;
            }
        }

        if (data != null) {

            ISkinnableEntityAdapter skAdapter = (ISkinnableEntityAdapter) data
                    .getAdapter(ISkinnableEntityAdapter.class);
            IMediaFileAdapter fileAdapter = (IMediaFileAdapter) data.getAdapter(IMediaFileAdapter.class);

            if (skAdapter != null && (skAdapter.isSkinned())) {
                ForwardUndoCompoundCommand command = new ForwardUndoCompoundCommand(
                        com.nokia.tools.s60.editor.commands.Messages.Clear_Label);
                command.add(skAdapter.getApplyBitmapPropertiesCommand(new BitmapProperties()));
                IColorAdapter ca = (IColorAdapter) data.getAdapter(IColorAdapter.class);
                if (ca != null) {
                    // extract color and set it
                    command.add(ca.getApplyColorCommand(ca.getColourFromGraphics(null), false));
                }
                if (fileAdapter != null) {
                    command.add(fileAdapter.getApplyDurationCommand(fileAdapter.getDurationFromGraphics()));
                    command.add(fileAdapter.getApplyMediaFileCommand(null));
                }

                ClearImageCommand cmd = null;
                //Set fireContentChanged argument to true if it is the last in the selection so that
                //required views gets refresh.
                if (els.hasNext()) {
                    cmd = new ClearImageCommand(data, editPart, partEntity, false);
                } else {
                    //last element in the selection
                    cmd = new ClearImageCommand(data, editPart, partEntity, true);
                }
                command.add(cmd);

                if (multi) {
                    multiCmdList.add(command);
                } else {
                    execute(command, getEditPart(obj));
                }
                IEditorPart activeEd = EclipseUtils.getActiveSafeEditor();
                if (activeEd instanceof Series60EditorPart) {
                    IFile original = ((FileEditorInput) activeEd.getEditorInput()).getFile();
                    ColorGroups grps = ColorGroupsStore.getColorGroupsForProject(original.getProject());
                    for (ColorGroup grp : grps.getGroups()) {
                        if (grp.containsItemWithIdAndLayerName(data.getId(), null)) {
                            //grp.removeItemFromGroup(data.getId(), null);
                            RemoveFromGroupCommand removeFromGroupCommand = new RemoveFromGroupCommand(
                                    data.getId(), null, grp, grps);
                            execute(removeFromGroupCommand, getEditPart(obj));
                            break;
                        }
                    }
                }

            }
        }

        // Support for clearing of audio changed/skinned elements
        if (data != null) {
            ISkinnableContentDataAdapter isca = (ISkinnableContentDataAdapter) data
                    .getAdapter(ISkinnableContentDataAdapter.class);
            if (isca != null) {
                Command clearSkinnedElementCommand = isca.getClearSkinnedElementCommand();
                if (multi) {
                    Command subCmdClear = clearSkinnedElementCommand;
                    multiCmdList.add(subCmdClear);
                } else {
                    execute(clearSkinnedElementCommand, editPart);
                }
            }
        }
    }

    if (multi && multiCmdList.size() > 0) {
        IRunnableWithProgress runnable = createRunnable(multiCmdList, editPart);
        //         ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(
        //               Display.getCurrent().getActiveShell());

        try {
            PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, false, runnable);
            //            progressMonitorDialog.run(true, false, runnable);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.nokia.tools.s60.editor.dnd.S60BaseDragListener.java

License:Open Source License

public void dragStart(DragSourceEvent event) {

    event.detail = DND.DROP_NONE;/* ww  w.  ja va  2 s . c  om*/
    if (transfer == LocalSelectionTransfer.getInstance()) {
        LocalSelectionTransfer.getInstance().setSelection(null);
    }

    Object selectedData = getSelectedElement(event);
    List<ClipboardContentDescriptor> extendedSelection = null;
    if (selectedData != null) {
        if (DNDUtil.isSelectionDraggeable(selectedData)) {

            IStructuredSelection selection = (IStructuredSelection) provider.getSelection();
            //items from selection            
            if (selection.size() > 1) {
                Object[] test = selection.toArray();
                Object matchedElement = null;
                for (Object item : test) {
                    if (equals(selectedData, item)) {
                        matchedElement = item;
                        break;
                    }
                }
                if (matchedElement != null) {

                    extendedSelection = new ArrayList<ClipboardContentDescriptor>();
                    extendedSelection.add(new ClipboardContentDescriptor(matchedElement,
                            ClipboardContentDescriptor.ContentType.CONTENT_ELEMENT));
                    for (int i = 0; i < test.length; i++) {
                        Object selContent = test[i];
                        if (selContent instanceof IContentData && selContent != matchedElement) {
                            ClipboardContentDescriptor ccd = new ClipboardContentDescriptor(selContent,
                                    ClipboardContentDescriptor.ContentType.CONTENT_ELEMENT);
                            extendedSelection.add(ccd);
                        }
                    }
                }
            }
        } else
            selectedData = null;
    }

    if (selectedData != null) {

        if (transfer == LocalSelectionTransfer.getInstance()) {

            List<ClipboardContentDescriptor> dragContent = null;

            if (extendedSelection == null) {
                dragContent = new ArrayList<ClipboardContentDescriptor>();
                ClipboardContentDescriptor ccd = new ClipboardContentDescriptor(selectedData,
                        ClipboardContentDescriptor.ContentType.CONTENT_ELEMENT);
                dragContent.add(ccd);
            } else {
                dragContent = extendedSelection;
            }

            eventDataLocal = new StructuredSelection(dragContent);
            eventDetail = DND.DROP_COPY;
            LocalSelectionTransfer.getInstance().setSelection((ISelection) eventDataLocal);
            LocalSelectionTransfer.getInstance().setSelectionSetTime(event.time & 0xFFFF);

        } else if (transfer instanceof FileTransfer) {

            if (extendedSelection == null) {
                extendedSelection = new ArrayList<ClipboardContentDescriptor>();
                extendedSelection.add(new ClipboardContentDescriptor(selectedData,
                        ClipboardContentDescriptor.ContentType.CONTENT_ELEMENT));
            }

            Clipboard clip = new Clipboard("");
            List<String> result = new ArrayList<String>();
            for (ClipboardContentDescriptor cc : extendedSelection) {
                selectedData = cc.getContent();
                CopyImageAction copyAction = new CopyImageAction(new SimpleSelectionProvider(selectedData),
                        clip);
                copyAction.setSilent(true);
                if (copyAction.isEnabled())
                    copyAction.run();
                Object possibleFile = ClipboardHelper.getSupportedClipboardContent(clip);
                if (possibleFile instanceof List) {
                    List files = (List) possibleFile;
                    for (Object item : files) {
                        if (item instanceof File)
                            result.add(((File) item).getAbsolutePath());
                    }
                }
            }
            if (result.size() > 0) {
                eventData = result.toArray(new String[result.size()]);
                eventDetail = DND.DROP_COPY;
            }
        }
    }
}

From source file:com.nokia.tools.s60.editor.ui.views.LayersPage.java

License:Open Source License

public void selectionChanged(IWorkbenchPart part, ISelection selection, SkinnableEntity skinnableEntity) {
    if (target != null) {
        target.eAdapters().remove(refreshAdapter);
    }/*from  w ww  . ja  v  a 2 s .co m*/
    try {
        if (part instanceof ColorsView) {
            return;
        }

        if (part instanceof PropertySheet || part instanceof Series60EditorPart && part != owningEditor)
            return;

        // ------------------------
        if (part == parentView || !(selection instanceof IStructuredSelection))
            return;

        IStructuredSelection structuredSelection = (IStructuredSelection) selection;
        boolean selectionIsList = false;
        boolean selectionIsListWithOneElement = false;
        if (structuredSelection.getFirstElement() instanceof List) {
            selectionIsList = true;
            List tempList = (List) (structuredSelection.getFirstElement());
            if (tempList.size() == 1) {
                selectionIsListWithOneElement = true;
            }
        }

        toggleColorModeAction.setEnabled(false);

        if (structuredSelection.size() == 1 && !(selectionIsList && !selectionIsListWithOneElement)) {

            // when selection contains valid contents -
            // EditPart or IContentData, refresh
            Object element = structuredSelection.getFirstElement();
            Object elementToSearch = null;
            if (element instanceof List) {
                elementToSearch = ((List) element).get(0);
            } else {
                elementToSearch = element;
            }
            IContentData cd = findContentData(elementToSearch);
            if (cd != null) {
                target = (EObject) cd.getAdapter(EditObject.class);
            }
            EditPart editPart = (EditPart) (elementToSearch instanceof EditPart ? elementToSearch : null);
            if (isAppTheme(editPart)) {
                _clearViewer();
                return;
            }

            if (cd != null) {

                try {

                    IToolBoxAdapter tba = (IToolBoxAdapter) cd.getAdapter(IToolBoxAdapter.class);
                    if (tba != null && tba.isFile()) {
                        _clearViewer();
                        return;
                    }

                    ISkinnableEntityAdapter sk = (ISkinnableEntityAdapter) cd
                            .getAdapter(ISkinnableEntityAdapter.class);

                    if (null != sk && sk.isColour() && !sk.hasImage()) {
                        IImageAdapter adapter = (IImageAdapter) cd.getAdapter(IImageAdapter.class);

                        IImage image = adapter == null ? null : adapter.getImage();
                        this.cdatas.clear();
                        this.currentParts.clear();
                        this.cdatas.add(cd);
                        this.currentParts.add(editPart);
                        image.removePropertyChangeListener(this);
                        image.addPropertyListener(this);
                        if (treeViewer.getInput() != image && treeViewerLabelProvider != null) {
                            treeViewerLabelProvider.flushImageCache();
                        }

                        try {
                            // parentSelectionIndex, ChildSelectionIndex
                            int[] tSIndex = { -1, -1 };

                            if (true == image.isMultiPiece()) {
                                if (skinnableEntity != null) {
                                    tSIndex = getTreeSelectionForMultipiece(skinnableEntity);
                                }
                            } else {
                                tSIndex = getTreeSelectionForSinglePiece();
                            }

                            treeViewer.setInput(image.getLayer(0).getLayerEffects().get(0));
                            treeViewer.expandAll();
                            makeTreeSelection(tSIndex);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return;
                    }

                    IImageAdapter adapter = (IImageAdapter) cd.getAdapter(IImageAdapter.class);
                    // adapter can be null for non-theme elements
                    IImage image = adapter == null ? null : adapter.getImage();

                    if (image != null) {
                        this.cdatas.clear();
                        this.currentParts.clear();
                        this.cdatas.add(cd);
                        this.currentParts.add(editPart);

                        image.removePropertyChangeListener(this);
                        image.addPropertyListener(this);
                        if (treeViewer.getInput() != image && treeViewerLabelProvider != null) {
                            treeViewerLabelProvider.flushImageCache();
                        }

                        // parentSelectionIndex, ChildSelectionIndex
                        int[] tSIndex = { -1, -1 };

                        if (true == image.isMultiPiece()) {
                            if (skinnableEntity != null) {
                                tSIndex = getTreeSelectionForMultipiece(skinnableEntity);
                            }
                        } else {
                            tSIndex = getTreeSelectionForSinglePiece();
                        }

                        treeViewer.setInput(image);
                        treeViewer.expandAll();
                        makeTreeSelection(tSIndex);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            // when selection contains valid multiselection contents -
            // EditParts or IContentDatas, refresh
            Object[] elements = structuredSelection.toArray();
            ArrayList<IImage> images = new ArrayList<IImage>();
            if (elements.length > 0) {
                this.cdatas = new ArrayList<IContentData>();
                this.currentParts = new ArrayList<EditPart>();

                if (elements[0] instanceof List) {
                    elements = ((List) elements[0]).toArray();
                }
            }
            for (Object element : elements) {
                IContentData cd = findContentData(element);
                if (cd != null) {
                    EObject object = (EObject) cd.getAdapter(EditObject.class);
                    if (object != null) {
                        target = object;
                    }
                }
                EditPart editPart = (EditPart) (element instanceof EditPart ? element : null);

                try {
                    if (null == cd) {
                        _clearViewer();
                        return;
                    }

                    IToolBoxAdapter tba = (IToolBoxAdapter) cd.getAdapter(IToolBoxAdapter.class);
                    if (tba != null && tba.isFile()) {
                        _clearViewer();
                        return;
                    }

                    IImageAdapter adapter = (IImageAdapter) cd.getAdapter(IImageAdapter.class);
                    // adapter can be null for non-theme elements
                    IImage image = adapter == null ? null : adapter.getImage();

                    if (image != null) {
                        this.currentParts.add(editPart);
                        this.cdatas.add(cd);

                        image.removePropertyChangeListener(this);
                        image.addPropertyListener(this);

                        images.add(image);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            treeViewerLabelProvider.flushImageCache();
            treeViewer.setInput(images);
            treeViewer.expandAll();
        }
        // ------------------------

        SimpleSelectionProvider ssp = new SimpleSelectionProvider((cdatas.size() == 1) ? cdatas.get(0) : null);
        clearAction.setSelectionProvider(ssp);
        clearAction.update();
        animateAction.setSelectionProvider(ssp);
        animateAction.update();
    } finally {
        if (target != null) {
            target.eAdapters().add(refreshAdapter);
        }
    }
}

From source file:com.nokia.tools.s60.views.IconViewPage.java

License:Open Source License

protected void repopulateContents(final IStructuredSelection ssel) {
    // keeps the last selection, so we can refresh the entire category when
    // some children have been added or removed
    lastSelection = ssel;//from   w  w  w  .j a  v  a 2  s .co m
    for (EditObject resource : resources) {
        ComponentAdapter adapter = (ComponentAdapter) EcoreUtil.getExistingAdapter(resource,
                ComponentAdapter.class);
        resource.eAdapters().remove(adapter);
    }
    resources.clear();

    if (container == null || container.isDisposed()) {
        return;
    }
    clearArea();
    Set<IContentData> selection = new HashSet<IContentData>();
    if (ssel != null) {
        for (Iterator iter = ssel.iterator(); iter.hasNext();) {
            Object obj = iter.next();
            if (obj instanceof IContentData) {
                selection.add((IContentData) obj);
            }
        }
    }

    List<Object> newSelection = new ArrayList<Object>();

    // populate all leafs of category
    try {
        List<IContentData> childrenList = getItems();
        for (final IContentData child : childrenList) {
            final ImageLabel control = new ImageLabel(container, SWT.NONE);
            control.setUnselectedBackground(container.getBackground());
            control.setSelectedBackground(container.getBackground());
            control.setData(child);
            control.addKeyListener(IconViewPage.this);
            EditObject resource = (EditObject) child.getAdapter(EditObject.class);
            resource.eAdapters().add(new ComponentAdapter(control));
            resources.add(resource);
            IContentData parent = child.getParent();
            if (parent != null) {
                EditObject parentResource = (EditObject) parent.getAdapter(EditObject.class);
                if (parentResource != null
                        && EcoreUtil.getExistingAdapter(parentResource, ComponentAdapter.class) == null) {
                    parentResource.eAdapters().add(new ComponentAdapter(null));
                    resources.add(parentResource);
                }
            }
            if (toggleTextAction != null) {
                control.setLines(toggleTextAction.isChecked() ? IS60IDEConstants.IMAGE_LABEL_TEXT_LINES : 0);
            }
            ISkinnableEntityAdapter ska = (ISkinnableEntityAdapter) child
                    .getAdapter(ISkinnableEntityAdapter.class);
            control.setModified(ska != null && ska.isSkinned());
            ISkinnableContentDataAdapter scda = (ISkinnableContentDataAdapter) child
                    .getAdapter(ISkinnableContentDataAdapter.class);
            if (scda != null) {
                control.setModified(scda.isElementSkinned());
                control.redraw();
            }

            if (selection.contains(child)) {
                newSelection.add(child);
                control.setSelected(true);
            }
            mouseRightClicked = false;

            // look if we can get right image, if not,
            // get default
            control.setImageDescriptor(getImageDescriptor(child));
            control.setText(child.getName());

            IconTooltip tooltip = new IconTooltip(findScreenData(child), this, getCommandStack());
            control.setData(tooltip.getClass().getName(), tooltip);
            if (tooltip.getContributionsCount(false) == 0) {
                // no tooltip contribution 
                // so use standard tooltip
                control.setToolTipText(child.getName());
            } else {
                tooltip.setControl(control);
            }

            control.addSelectionListener(new ImageLabel.SelectedListener() {
                public void selected(EventObject e) {
                    if (!selectedItems.contains(((ImageLabel) e.getSource()).getData())) {
                        ((ImageLabel) e.getSource()).setSelected(false);
                    }
                }
            });

            control.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseDown(MouseEvent e) {
                    mouseButtonDown(e);

                    if (e.button == 3) {
                        mouseRightClicked = true;
                    }

                    final IconTooltip tooltip = (IconTooltip) control.getData(IconTooltip.class.getName());

                    if (tooltip != null) {
                        if (e.button == 3) {
                            tooltip.hide();
                        }
                        tooltip.disable();
                        Display.getDefault().asyncExec(new Runnable() {
                            public void run() {
                                if (tooltip != null) {
                                    tooltip.enable();
                                }
                            }
                        });
                    }
                }

                @Override
                public void mouseUp(MouseEvent e) {
                    if (mouseButtonUp(e)) {
                        return;
                    }
                    if (e.button == 1) {
                        if (ctrl_active && shift_active) {
                            updateSelection(child, SelectionMode.CTRL_SHIFT);
                        } else if (shift_active) {
                            updateSelection(child, SelectionMode.SHIFT);
                        } else if (ctrl_active) {
                            updateSelection(child, SelectionMode.CTRL);
                        } else {
                            selectionStart = child;
                            selfSetSelection(new StructuredSelection(child));
                        }
                    } else if (e.button == 3) {
                        if (selectedItems == null || !selectedItems.contains(child)) {
                            selectionStart = child;
                            updateSelection(child, SelectionMode.NORMAL);
                        }
                    }
                    mouseRightClicked = false;
                }

                @Override
                public void mouseDoubleClick(MouseEvent e) {
                    if (e.count == 2) {
                        handleDoubleClick(child);
                    }
                }
            });

            MouseMoveListener mouseMoveListener = new MouseMoveListener() {
                public void mouseMove(MouseEvent e) {
                    mouseMoved(e);
                }
            };

            control.addMouseMoveListener(mouseMoveListener);

            MenuManager menuMgr = new MenuManager("#PopupMenu");
            menuMgr.setRemoveAllWhenShown(true);
            menuMgr.addMenuListener(new IMenuListener() {
                public void menuAboutToShow(IMenuManager manager) {
                    IIconMenuProvider imp = (IIconMenuProvider) sourceEditor
                            .getAdapter(IIconMenuProvider.class);
                    if (imp != null) {
                        imp.fillIconContextMenu(manager, IconViewPage.this.parent, "components",
                                getCommandStack(), getSite().getActionBars());
                    }
                }
            });

            Menu menu = menuMgr.createContextMenu(control);
            control.setMenu(menu);

            // drag and drop support
            addDragDropSupport(control, child);
        }

        if (container != null && !container.isDisposed()) {
            container.layout();
            scrollableComposite.setMinSize(container.computeSize(SWT.DEFAULT, SWT.DEFAULT));
            container.redraw();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // add flags about synchronize with editor
    if (ssel.size() > 0 && ssel.toArray()[ssel.size() - 1] == Boolean.FALSE)
        newSelection.add(Boolean.FALSE);
    setSelection(new StructuredSelection(newSelection));
}

From source file:com.nokia.tools.s60.views.IconViewPage.java

License:Open Source License

/**
 * Called from resource view to set icon-set to be displayed
 *///from ww  w.  j a va 2 s.  c  om
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    if (!listenOnSelection || part instanceof IconView) {
        return;
    }

    //  selections from resource viewer
    // if (part instanceof ResourceViewPart || part == null) {
    // if (selection instanceof IStructuredSelection && !(part instanceof
    // IconView)) {
    if (selection instanceof IStructuredSelection) {
        IStructuredSelection sel = (IStructuredSelection) selection;
        if (sel.size() == 0) {
            return;
        }

        // convert edit parts to content data
        // filters out the duplicates
        Set<Object> set = new HashSet<Object>(sel.size());
        for (Object object : sel.toArray()) {
            IContentData data = null;
            if (object instanceof EditPart || object instanceof IScreenElement) {
                data = findModelItem(object);
            } else if (object instanceof IContentData) {
                data = (IContentData) object;
            }
            if (data != null) {
                ISkinnableEntityAdapter ca = (ISkinnableEntityAdapter) data
                        .getAdapter(ISkinnableEntityAdapter.class);
                if (ca != null) {
                    // cares only about the skinnable entities
                    set.add(data);
                }
            }
        }

        if (set.isEmpty()) {
            //  clears the view
            initializePage(StructuredSelection.EMPTY, null, null);
            repopulateContents(StructuredSelection.EMPTY);
            return;
        }
        List<Object> cdSel = new ArrayList<Object>(set.size());
        for (Object obj : set) {
            cdSel.add(obj);
        }

        // selection raised from editor,
        // editor
        if (part == sourceEditor) {
            cdSel.add(Boolean.FALSE);
        }

        sel = new StructuredSelection(cdSel);

        List<Object> newSelection = new ArrayList<Object>();

        if (ctrl_active || shift_active) {
            // preserve selection
            // add non-visible elements from current component view
            // selection
            List<IContentData> nonVisuals = new ArrayList<IContentData>();
            for (int i = 0; selectedItems != null && i < selectedItems.size(); i++) {
                IContentData data = selectedItems.get(i);
                if (!isVisibleOnScreen(data)) {
                    nonVisuals.add(data);
                }
            }

            List<Object> _selection = new ArrayList<Object>();
            _selection.addAll(Arrays.asList(sel.toArray()));

            if (selectedItems != null) {
                newSelection.addAll(selectedItems);
            }

            // add added elements
            for (int i = 0; i < _selection.size(); i++) {
                Object obj = _selection.get(i);
                if (!newSelection.contains(obj) || obj instanceof Boolean) {
                    newSelection.add(obj);
                }
            }

            // remove removed elements
            for (int i = 0; selectedItems != null && i < selectedItems.size(); i++) {
                Object obj = selectedItems.get(i);
                if (!_selection.contains(obj)) {
                    // preserve non-visible
                    if (!nonVisuals.contains(obj)) {
                        newSelection.remove(obj);
                    }
                }
            }
        } else {
            newSelection = sel.toList();
        }

        final StructuredSelection newSel = new StructuredSelection(newSelection);

        if (sel.size() == 0 || (sel.size() > 0 && sel.getFirstElement() instanceof IContentData)) {
            IContentData tmpData = (IContentData) (sel.getFirstElement());
            if (tmpData != null
                    && (tmpData.getParent() instanceof IContent
                            || tmpData.getAdapter(IScreenAdapter.class) != null)
                    || tmpData instanceof ThemeScreenReferData) {
                return;
            }
            IContentAdapter adapter = (IContentAdapter) sourceEditor.getAdapter(IContentAdapter.class);
            IContent content = ScreenUtil.getPrimaryContent(adapter.getContents());
            if (tmpData != null && !(tmpData.getRoot() instanceof IContent)) {
                // removed from the content
                tmpData = content.findById(tmpData.getId());
            }
            final IContentData newCategory = sel.size() == 0 || tmpData == null ? null : tmpData.getParent();
            com.nokia.tools.platform.core.Display newDisplay = (com.nokia.tools.platform.core.Display) content
                    .getAttribute(ContentAttribute.DISPLAY.name());
            final Dimension newResolution = newDisplay == null ? null
                    : new Dimension(newDisplay.getWidth(), newDisplay.getHeight());

            if (currentCategory != newCategory || (newResolution != null && !newResolution.equals(resolution))
                    || currentCategory == null || getItems().size() != container.getChildren().length) {
                initializePage(newSel, newCategory, newResolution);
                Display.getDefault().asyncExec(new Runnable() {
                    public void run() {
                        repopulateContents(newSel);
                    }
                });

                return;
            }
        }
        // always sets the selection because the selection on the main
        // editor might have changed
        setSelection(newSel);
    }

}

From source file:com.nokia.tools.s60.views.IconViewPage.java

License:Open Source License

public void setSelection(final ISelection selection) {
    if (container == null || container.isDisposed()) {
        return;//from ww  w  . ja va2 s. c o  m
    }
    if (suppressSelectEvent) {
        return;
    }
    if (currentCategory == null) {
        refreshIconViewActionsState();
        return;
    }

    if (selection instanceof IStructuredSelection) {

        final IStructuredSelection sselection = (IStructuredSelection) selection;

        /**
         * Should not be used as then when selection changes in editor the
         * same element can not be reselected but have to visit other
         * element first
         */

        if (selectedItems != null && selectedItems.size() == 1 && !selection.isEmpty()
                && selectedItems.get(0) == ((IStructuredSelection) selection).getFirstElement()) {
            itemReSelected = true;
        } else {
            itemReSelected = false;
        }

        List<IContentData> newSelection = new ArrayList<IContentData>();
        for (Iterator iter = sselection.iterator(); iter.hasNext();) {
            Object obj = iter.next();
            if (obj instanceof IContentData) {

                IContentData modelData = currentCategory.findById(((IContentData) obj).getId());
                if (modelData == null)
                    continue;
                // set screen context to theme data, will be needed to
                // creating
                // bean-widget for elements that don't have screen
                // element

                modelData.getAdapter(EditObject.class);
                newSelection.add(modelData);
            } else {
                // select from screen widgets
                IScreenElement se = JEMUtil.getScreenElement(obj);
                if (se != null) {
                    // handles colors
                    ICategoryAdapter ca = (ICategoryAdapter) se.getData().getAdapter(ICategoryAdapter.class);
                    IContentData[] peers = ca.getCategorizedPeers();
                    for (IContentData peer : peers) {
                        newSelection.add(peer);
                    }
                }
            }
        }

        selectedItems = newSelection;
        if (!selectedItems.contains(selectionStart)) {
            selectionStart = null;
        }

        // notifies listeners before revealing in the editor because the
        // statue line may otherwise be changed by other views
        suppressSelectEvent = true;
        try {
            SelectionChangedEvent event = new SelectionChangedEvent(this, getSelection());
            for (ISelectionChangedListener l : listeners) {
                try {
                    l.selectionChanged(event);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } finally {
            suppressSelectEvent = false;
        }

        Control[] controls = container.getChildren();

        IContentData last = newSelection.isEmpty() ? null : newSelection.get(newSelection.size() - 1);

        for (Control ctrl : controls) {
            ImageLabel label = (ImageLabel) ctrl;

            if (ctrl.getData() == last) {
                scrollToVisible(ctrl);
            }

            if (newSelection.contains(ctrl.getData())) {
                label.setSelected(true);
            } else {
                label.setSelected(false);
            }
        }

        if (synchronize) {

            if (!(sselection.size() > 0 && sselection.toArray()[sselection.size() - 1] == Boolean.FALSE)) {
                suppressSelectEvent = true;
                try {
                    showSelectionInEditor((IStructuredSelection) selection);
                } finally {
                    suppressSelectEvent = false;
                }
            }
        }
    }

    suppressSelectEvent = true;
    try {

        ((IconView) parent).fireSelectionChangeEvent();
    } finally {
        suppressSelectEvent = false;
    }

    refreshIconViewActionsState();
}

From source file:com.nokia.tools.s60.views.IconViewPage.java

License:Open Source License

private void initializeIconViewActions() {
    IActionBars bars = getSite().getActionBars();
    IToolBarManager tbm = bars.getToolBarManager();

    tbm.removeAll();//from  www  .j  a v a2 s  .c  o  m

    selectAllAction = new IconViewSelectAllAction(this);
    tbm.add(selectAllAction);

    tbm.add(new Separator());

    copyAction = new CopyImageAction(IconViewPage.this.parent, null);
    tbm.add(copyAction);

    pasteAction = new PasteImageAction(IconViewPage.this.parent, null);
    tbm.add(pasteAction);

    tbm.add(new Separator());

    browseForFileAction = new BrowseForFileAction(IconViewPage.this.parent);
    tbm.add(browseForFileAction);

    tbm.add(new Separator());

    animateAction = new OpenGraphicsEditorAction(parent, this);
    animateAction.listenSelection();
    animateAction.selectionChanged(null);
    tbm.add(animateAction);

    externalToolsDropDown = new IconViewDropDownToolbarAction(this);
    tbm.add(externalToolsDropDown);

    tbm.add(new Separator());

    clearAction = new ClearImageEditorAction(IconViewPage.this.parent);
    tbm.add(clearAction);

    tbm.add(new Separator());

    toggleTextAction = new ToggleTextAction(this);
    IPreferenceStore store = S60WorkspacePlugin.getDefault().getPreferenceStore();
    toggleTextAction.setChecked(store.getBoolean(IS60IDEConstants.PREF_SHOW_TITLE_TEXTS));
    tbm.add(toggleTextAction);

    Action toggleSync = new WorkbenchPartAction(null, WorkbenchPartAction.AS_CHECK_BOX) {
        @Override
        public void run() {
            if (synchronize) {
                synchronize = false;
            } else {
                synchronize = true;
                IStructuredSelection sselection = (IStructuredSelection) getSelection();
                if (sselection != null) {
                    if (!(sselection.size() > 0
                            && sselection.toArray()[sselection.size() - 1] == Boolean.FALSE)) {
                        suppressSelectEvent = true;
                        try {
                            showSelectionInEditor((IStructuredSelection) getSelection());
                        } finally {
                            suppressSelectEvent = false;
                        }
                    }
                }
            }
            IPreferenceStore store = S60WorkspacePlugin.getDefault().getPreferenceStore();
            store.setValue(IS60IDEConstants.PREF_SYNC_WITH_EDITOR, synchronize);
        }

        @Override
        protected boolean calculateEnabled() {
            return true;
        }
    };

    ImageDescriptor i1 = UiPlugin.getIconImageDescriptor("resview_toggle_synch.gif", true);
    toggleSync.setToolTipText(ViewMessages.IconView_toggleSync_tooltip);
    toggleSync.setImageDescriptor(i1);
    tbm.add(new Separator());
    tbm.add(toggleSync);

    // Restore last synchronization state
    boolean syncState = store.getBoolean(IS60IDEConstants.PREF_SYNC_WITH_EDITOR);
    synchronize = !syncState;
    toggleSync.setChecked(syncState);
    toggleSync.run();

    /* global action handlers */

    setGlobalHandler(bars, new PasteContentDataAction(this, getCommandStack(), null));
    setGlobalHandler(bars, new EditImageInSVGEditorAction(this, getCommandStack()));
    setGlobalHandler(bars, new EditImageInBitmapEditorAction(this, getCommandStack()));
    setGlobalHandler(bars, new NinePieceConvertAction(this, getCommandStack(), 9));
    setGlobalHandler(bars, new NinePieceConvertAction(this, getCommandStack(), 1));

    setGlobalHandler(bars, new ElevenPieceConvertAction(this, getCommandStack(), 11));
    setGlobalHandler(bars, new ElevenPieceConvertAction(this, getCommandStack(), 1));

    /*setGlobalHandler(bars, new ThreePieceConvertAction(this,
    getCommandStack(), 3));
    setGlobalHandler(bars, new ThreePieceConvertAction(this,
    getCommandStack(), 1));*/

    setGlobalHandler(bars, new ConvertAndEditSVGInBitmapEditorAction(this, getCommandStack()));
    setGlobalHandler(bars, new EditInSystemEditorAction(this, getCommandStack()));
    setGlobalHandler(bars, new EditMaskAction(this, getCommandStack()));
    setGlobalHandler(bars, new EditMaskAction2(this, getCommandStack()));
    setGlobalHandler(bars, new EditSoundInSoundEditorAction(this, getCommandStack()));
    setGlobalHandler(bars, new BrowseForFileAction(this, getCommandStack()));
    setGlobalHandler(bars,
            new SetStretchModeAction(this, getCommandStack(), IMediaConstants.STRETCHMODE_STRETCH));
    setGlobalHandler(bars,
            new SetStretchModeAction(this, getCommandStack(), IMediaConstants.STRETCHMODE_ASPECT));

    // undo, redo

    ActionRegistry ar = (ActionRegistry) sourceEditor.getAdapter(ActionRegistry.class);
    if (ar != null) {
        bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), ar.getAction(ActionFactory.UNDO.getId()));
        bars.setGlobalActionHandler(ActionFactory.REDO.getId(), ar.getAction(ActionFactory.REDO.getId()));
    } else {
        IAction action = new SafeUndoAction(parent);
        bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), action);
        action = new SafeRedoAction(parent);
        bars.setGlobalActionHandler(ActionFactory.REDO.getId(), action);
    }

    /* add task, add bookmark */
    setGlobalHandler(bars, new AddTaskViewAction(parent));
    setGlobalHandler(bars, new AddBookmarkViewAction(parent));

    // clear element, edit/animate, copy, paste
    bars.setGlobalActionHandler(OpenGraphicsEditorAction.ID, animateAction);
    bars.setGlobalActionHandler(ClearImageEditorAction.ID, clearAction);
    bars.setGlobalActionHandler(PasteImageAction.ID, pasteAction);
    bars.setGlobalActionHandler(CopyImageAction.ID, copyAction);
}