Example usage for org.eclipse.jface.viewers TreeViewer setSelection

List of usage examples for org.eclipse.jface.viewers TreeViewer setSelection

Introduction

In this page you can find the example usage for org.eclipse.jface.viewers TreeViewer setSelection.

Prototype

@Override
    protected void setSelection(List<Item> items) 

Source Link

Usage

From source file:de.walware.ecommons.ui.workbench.AbstractEditorOutlinePage.java

License:Open Source License

@Override
public void setSelection(final ISelection selection) {
    final TreeViewer viewer = getViewer();
    if (UIAccess.isOkToUse(viewer)) {
        viewer.setSelection(selection);
    }//from www  .j  ava 2  s  .  c om
}

From source file:descent.internal.ui.wizards.buildpaths.FolderSelectionDialog.java

License:Open Source License

protected void newFolderButtonPressed() {
    NewFolderDialog dialog = new NewFolderDialog(getShell(), fSelectedContainer) {
        protected Control createContents(Composite parent) {
            PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IJavaHelpContextIds.BP_CREATE_NEW_FOLDER);
            return super.createContents(parent);
        }/*from   w  ww . j av  a2 s. c o  m*/
    };
    if (dialog.open() == Window.OK) {
        TreeViewer treeViewer = getTreeViewer();
        treeViewer.refresh(fSelectedContainer);
        Object createdFolder = dialog.getResult()[0];
        treeViewer.reveal(createdFolder);
        treeViewer.setSelection(new StructuredSelection(createdFolder));
    }
}

From source file:es.cv.gvcase.emf.ui.common.dialogs.FeatureEditorDialog.java

License:Open Source License

@Override
protected Control createDialogArea(Composite parent) {
    Composite contents = (Composite) super.createDialogArea(parent);

    GridLayout contentsGridLayout = (GridLayout) contents.getLayout();
    contentsGridLayout.numColumns = 3;//  ww  w. j  ava  2s  . com

    GridData contentsGridData = (GridData) contents.getLayoutData();
    contentsGridData.horizontalAlignment = SWT.FILL;
    contentsGridData.verticalAlignment = SWT.FILL;

    Text patternText = null;

    if (choiceOfValues != null) {
        Group filterGroupComposite = new Group(contents, SWT.NONE);
        filterGroupComposite.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Choices_pattern_group"));
        filterGroupComposite.setLayout(new GridLayout(2, false));
        filterGroupComposite.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false, 3, 1));

        Label label = new Label(filterGroupComposite, SWT.NONE);
        label.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Choices_pattern_label"));

        patternText = new Text(filterGroupComposite, SWT.BORDER);
        patternText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    }

    Composite choiceComposite = new Composite(contents, SWT.NONE);
    {
        GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
        data.horizontalAlignment = SWT.END;
        choiceComposite.setLayoutData(data);

        GridLayout layout = new GridLayout();
        data.horizontalAlignment = SWT.FILL;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.numColumns = 1;
        choiceComposite.setLayout(layout);
    }

    Label choiceLabel = new Label(choiceComposite, SWT.NONE);
    choiceLabel.setText(choiceOfValues == null ? EMFEditUIPlugin.INSTANCE.getString("_UI_Value_label")
            : EMFEditUIPlugin.INSTANCE.getString("_UI_Choices_label"));
    GridData choiceLabelGridData = new GridData();
    choiceLabelGridData.verticalAlignment = SWT.FILL;
    choiceLabelGridData.horizontalAlignment = SWT.FILL;
    choiceLabel.setLayoutData(choiceLabelGridData);

    final Tree choiceTree = choiceOfValues == null ? null : new Tree(choiceComposite, SWT.MULTI | SWT.BORDER);
    if (choiceTree != null) {
        GridData choiceTtreeGridData = new GridData();
        choiceTtreeGridData.widthHint = Display.getCurrent().getBounds().width / 5;
        choiceTtreeGridData.heightHint = Display.getCurrent().getBounds().height / 3;
        choiceTtreeGridData.verticalAlignment = SWT.FILL;
        choiceTtreeGridData.horizontalAlignment = SWT.FILL;
        choiceTtreeGridData.grabExcessHorizontalSpace = true;
        choiceTtreeGridData.grabExcessVerticalSpace = true;
        choiceTree.setLayoutData(choiceTtreeGridData);
    }

    final TreeViewer choiceTreeViewer = choiceOfValues == null ? null : new TreeViewer(choiceTree);
    if (choiceTreeViewer != null) {
        choiceTreeViewer.setContentProvider(contentProvider);
        choiceTreeViewer.setLabelProvider(labelProvider);
        final PatternFilter filter = new PatternFilter() {
            @Override
            protected boolean isParentMatch(Viewer viewer, Object element) {
                return viewer instanceof AbstractTreeViewer && super.isParentMatch(viewer, element);
            }
        };
        choiceTreeViewer.addFilter(filter);
        assert patternText != null;
        patternText.addModifyListener(new ModifyListener() {
            public void modifyText(ModifyEvent e) {
                filter.setPattern(((Text) e.widget).getText());
                choiceTreeViewer.refresh();
            }
        });
        choiceTreeViewer.setInput(choiceOfValues);

        choiceTreeViewer.expandToLevel(2);
    }

    // We use multi even for a single line because we want to respond to the
    // enter key.
    //
    int style = multiLine ? SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER : SWT.MULTI | SWT.BORDER;
    final Text choiceText = choiceOfValues == null ? new Text(choiceComposite, style) : null;
    if (choiceText != null) {
        GridData choiceTextGridData = new GridData();
        choiceTextGridData.widthHint = Display.getCurrent().getBounds().width / 5;
        choiceTextGridData.verticalAlignment = SWT.BEGINNING;
        choiceTextGridData.horizontalAlignment = SWT.FILL;
        choiceTextGridData.grabExcessHorizontalSpace = true;
        if (multiLine) {
            choiceTextGridData.verticalAlignment = SWT.FILL;
            choiceTextGridData.grabExcessVerticalSpace = true;
        }
        choiceText.setLayoutData(choiceTextGridData);
    }

    Composite controlButtons = new Composite(contents, SWT.NONE);
    GridData controlButtonsGridData = new GridData();
    controlButtonsGridData.verticalAlignment = SWT.FILL;
    controlButtonsGridData.horizontalAlignment = SWT.FILL;
    controlButtons.setLayoutData(controlButtonsGridData);

    GridLayout controlsButtonGridLayout = new GridLayout();
    controlButtons.setLayout(controlsButtonGridLayout);

    new Label(controlButtons, SWT.NONE);

    final Button addButton = new Button(controlButtons, SWT.PUSH);
    addButton.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Add_label"));
    GridData addButtonGridData = new GridData();
    addButtonGridData.verticalAlignment = SWT.FILL;
    addButtonGridData.horizontalAlignment = SWT.FILL;
    addButton.setLayoutData(addButtonGridData);

    final Button removeButton = new Button(controlButtons, SWT.PUSH);
    removeButton.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Remove_label"));
    GridData removeButtonGridData = new GridData();
    removeButtonGridData.verticalAlignment = SWT.FILL;
    removeButtonGridData.horizontalAlignment = SWT.FILL;
    removeButton.setLayoutData(removeButtonGridData);

    Label spaceLabel = new Label(controlButtons, SWT.NONE);
    GridData spaceLabelGridData = new GridData();
    spaceLabelGridData.verticalSpan = 2;
    spaceLabel.setLayoutData(spaceLabelGridData);

    final Button upButton = new Button(controlButtons, SWT.PUSH);
    upButton.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Up_label"));
    GridData upButtonGridData = new GridData();
    upButtonGridData.verticalAlignment = SWT.FILL;
    upButtonGridData.horizontalAlignment = SWT.FILL;
    upButton.setLayoutData(upButtonGridData);

    final Button downButton = new Button(controlButtons, SWT.PUSH);
    downButton.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Down_label"));
    GridData downButtonGridData = new GridData();
    downButtonGridData.verticalAlignment = SWT.FILL;
    downButtonGridData.horizontalAlignment = SWT.FILL;
    downButton.setLayoutData(downButtonGridData);

    Composite featureComposite = new Composite(contents, SWT.NONE);
    {
        GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
        data.horizontalAlignment = SWT.END;
        featureComposite.setLayoutData(data);

        GridLayout layout = new GridLayout();
        data.horizontalAlignment = SWT.FILL;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.numColumns = 1;
        featureComposite.setLayout(layout);
    }

    Label featureLabel = new Label(featureComposite, SWT.NONE);
    featureLabel.setText(EMFEditUIPlugin.INSTANCE.getString("_UI_Feature_label"));
    GridData featureLabelGridData = new GridData();
    featureLabelGridData.horizontalSpan = 2;
    featureLabelGridData.horizontalAlignment = SWT.FILL;
    featureLabelGridData.verticalAlignment = SWT.FILL;
    featureLabel.setLayoutData(featureLabelGridData);

    final Tree featureTree = new Tree(featureComposite, SWT.MULTI | SWT.BORDER);
    GridData featureTreeGridData = new GridData();
    featureTreeGridData.widthHint = Display.getCurrent().getBounds().width / 5;
    featureTreeGridData.heightHint = Display.getCurrent().getBounds().height / 3;
    featureTreeGridData.verticalAlignment = SWT.FILL;
    featureTreeGridData.horizontalAlignment = SWT.FILL;
    featureTreeGridData.grabExcessHorizontalSpace = true;
    featureTreeGridData.grabExcessVerticalSpace = true;
    featureTree.setLayoutData(featureTreeGridData);

    final TreeViewer featureTreeViewer = new TreeViewer(featureTree);
    featureTreeViewer.setContentProvider(contentProvider);
    featureTreeViewer.setLabelProvider(labelProvider);
    if (values != null) {
        featureTreeViewer.setInput(values);
        if (!values.getChildren().isEmpty()) {
            featureTreeViewer.setSelection(new StructuredSelection(values.getChildren().get(0)));
        }
    } else {
        featureTreeViewer.setInput(currentValues);
        if (!currentValues.isEmpty()) {
            featureTreeViewer.setSelection(new StructuredSelection(currentValues.get(0)));
        }
    }
    featureTreeViewer.expandToLevel(2);

    if (choiceTreeViewer != null) {
        choiceTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
            public void doubleClick(DoubleClickEvent event) {
                if (addButton.isEnabled()) {
                    addButton.notifyListeners(SWT.Selection, null);
                }
            }
        });

        featureTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
            public void doubleClick(DoubleClickEvent event) {
                if (removeButton.isEnabled()) {
                    removeButton.notifyListeners(SWT.Selection, null);
                }
            }
        });
    }

    if (choiceText != null) {
        choiceText.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent event) {
                if (!multiLine && (event.character == '\r' || event.character == '\n')) {
                    try {
                        Object value = EcoreUtil.createFromString((EDataType) eClassifier,
                                choiceText.getText());
                        if (values != null) {
                            values.getChildren().add(value);
                        } else {
                            currentValues.add(value);
                        }
                        choiceText.setText("");
                        featureTreeViewer.setSelection(new StructuredSelection(value));
                        event.doit = false;
                    } catch (RuntimeException exception) {
                        // Ignore
                    }
                } else if (event.character == '\33') {
                    choiceText.setText("");
                    event.doit = false;
                }
            }
        });
    }

    upButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            IStructuredSelection selection = (IStructuredSelection) featureTreeViewer.getSelection();
            int minIndex = 0;
            for (Iterator<?> i = selection.iterator(); i.hasNext();) {
                Object value = i.next();
                if (values != null) {
                    int index = values.getChildren().indexOf(value);
                    values.getChildren().move(Math.max(index - 1, minIndex++), value);
                } else {
                    int index = currentValues.indexOf(value);
                    currentValues.remove(value);
                    currentValues.add(Math.max(index - 1, minIndex++), value);
                }
            }
            featureTreeViewer.refresh();
            featureTreeViewer.expandToLevel(2);
            featureTreeViewer.setSelection(selection);
        }
    });

    downButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            IStructuredSelection selection = (IStructuredSelection) featureTreeViewer.getSelection();
            int maxIndex = 0;
            if (values != null) {
                maxIndex = values.getChildren().size();
            } else {
                maxIndex = currentValues.size();
            }
            maxIndex = maxIndex - selection.size();
            for (Iterator<?> i = selection.iterator(); i.hasNext();) {
                Object value = i.next();
                if (values != null) {
                    int index = values.getChildren().indexOf(value);
                    values.getChildren().move(Math.min(index + 1, maxIndex++), value);
                } else {
                    int index = currentValues.indexOf(value);
                    currentValues.remove(value);
                    currentValues.add(Math.min(index + 1, maxIndex++), value);
                }
            }
            featureTreeViewer.refresh();
            featureTreeViewer.expandToLevel(2);
            featureTreeViewer.setSelection(selection);
        }
    });

    addButton.addSelectionListener(new SelectionAdapter() {
        // event is null when choiceTableViewer is double clicked
        @Override
        public void widgetSelected(SelectionEvent event) {
            if (choiceTreeViewer != null) {
                IStructuredSelection selection = (IStructuredSelection) choiceTreeViewer.getSelection();
                for (Iterator<?> i = selection.iterator(); i.hasNext();) {
                    Object value = i.next();
                    if (!eClassifier.isInstance(value)) {
                        continue;
                    }
                    if (values != null) {
                        if (!values.getChildren().contains(value)) {
                            values.getChildren().add(value);
                        }
                    } else {
                        if (!currentValues.contains(value)) {
                            currentValues.add(value);
                        }
                    }
                }
                featureTreeViewer.refresh();
                featureTreeViewer.expandToLevel(2);
                featureTreeViewer.setSelection(selection);
            } else if (choiceText != null) {
                try {
                    Object value = EcoreUtil.createFromString((EDataType) eClassifier, choiceText.getText());
                    if (values != null) {
                        values.getChildren().add(value);
                    } else {
                        currentValues.add(value);
                    }
                    choiceText.setText("");
                    featureTreeViewer.refresh(value);
                    featureTreeViewer.setSelection(new StructuredSelection(value));
                } catch (RuntimeException exception) {
                    // Ignore
                }
            }
        }
    });

    removeButton.addSelectionListener(new SelectionAdapter() {
        // event is null when featureTableViewer is double clicked
        @Override
        public void widgetSelected(SelectionEvent event) {
            IStructuredSelection selection = (IStructuredSelection) featureTreeViewer.getSelection();
            Object firstValue = null;
            for (Iterator<?> i = selection.iterator(); i.hasNext();) {
                Object value = i.next();
                if (!eClassifier.isInstance(value)) {
                    continue;
                }
                if (firstValue == null) {
                    firstValue = value;
                }
                if (values != null) {
                    values.getChildren().remove(value);
                } else {
                    currentValues.remove(value);
                }
            }

            if (values != null) {
                if (!values.getChildren().isEmpty()) {
                    featureTreeViewer.setSelection(new StructuredSelection(values.getChildren().get(0)));
                }
            } else {
                if (!currentValues.isEmpty()) {
                    featureTreeViewer.setSelection(new StructuredSelection(currentValues.get(0)));
                }
            }

            if (choiceTreeViewer != null) {
                choiceTreeViewer.refresh();
                choiceTreeViewer.expandToLevel(2);
                featureTreeViewer.refresh();
                featureTreeViewer.expandToLevel(2);
                choiceTreeViewer.setSelection(selection);
            } else if (choiceText != null) {
                if (firstValue != null) {
                    String value = EcoreUtil.convertToString((EDataType) eClassifier, firstValue);
                    choiceText.setText(value);
                }
            }
        }
    });

    return contents;
}

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  w  w.  j a  v a  2  s  .co m*/
 * @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:eu.esdihumboldt.hale.ui.codelist.inspire.internal.CodeListSelectionDialog.java

License:Open Source License

/**
 * @see AbstractViewerSelectionDialog#setupViewer(StructuredViewer, Object)
 *//*  w w w. j  a  v a 2 s.  c o m*/
@Override
protected void setupViewer(final TreeViewer viewer, final CodeListRef initialSelection) {
    viewer.setLabelProvider(new CodeListLabelProvider());
    viewer.setContentProvider(new CodeListContentProvider());

    ProgressMonitorDialog dlg = new ProgressMonitorDialog(getShell());
    final Display display = Display.getCurrent();
    try {
        dlg.run(true, false, new IRunnableWithProgress() {

            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask("Loading available code lists from INSPIRE registry",
                        IProgressMonitor.UNKNOWN);

                final Collection<CodeListRef> codeLists = RegistryCodeLists.loadCodeLists().values();

                display.asyncExec(new Runnable() {

                    @Override
                    public void run() {
                        viewer.setInput(codeLists);

                        if (initialSelection != null) {
                            viewer.setSelection(new StructuredSelection(initialSelection));
                        }
                    }
                });

                monitor.done();
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        throw new IllegalStateException("Failed to load code lists", e);
    }
}

From source file:eu.esdihumboldt.hale.ui.common.definition.selector.PropertyDefinitionDialog.java

License:Open Source License

@Override
protected void setupViewer(TreeViewer viewer, EntityDefinition initialSelection) {
    viewer.setLabelProvider(new DefinitionLabelProvider());
    viewer.setContentProvider(new TreePathProviderAdapter(new TypePropertyContentProvider(viewer)));

    viewer.setInput(parentType);//from   w ww  .ja  v a2 s  .  c  o  m

    if (initialSelection != null) {
        viewer.setSelection(new StructuredSelection(initialSelection));
    }
}

From source file:eu.esdihumboldt.hale.ui.common.definition.selector.TypeDefinitionDialog.java

License:Open Source License

@Override
protected void setupViewer(TreeViewer viewer, TypeDefinition initialSelection) {
    viewer.setLabelProvider(new DefinitionLabelProvider());
    viewer.setContentProvider(new TypesContentProvider(viewer));

    viewer.setInput(types);/*from w ww .  j a v a 2  s  .  co m*/

    if (initialSelection != null) {
        viewer.setSelection(new StructuredSelection(initialSelection));
    }
}

From source file:eu.esdihumboldt.hale.ui.function.common.PropertyEntityDialog.java

License:Open Source License

/**
 * @see EntityDialog#setupViewer(TreeViewer, EntityDefinition)
 *//*from ww  w .  ja  va  2s  .c  o  m*/
@Override
protected void setupViewer(TreeViewer viewer, EntityDefinition initialSelection) {
    viewer.setLabelProvider(new StyledDefinitionLabelProvider());
    EntityDefinitionService entityDefinitionService = (EntityDefinitionService) PlatformUI.getWorkbench()
            .getService(EntityDefinitionService.class);

    if (parentType != null) {
        viewer.setContentProvider(new TreePathProviderAdapter(
                new EntityTypePropertyContentProvider(entityDefinitionService, ssid)));
        viewer.setInput(parentType);
    } else {
        flatRelevantProvider = new TreePathProviderAdapter(
                new EntityTypeIndexContentProvider(entityDefinitionService, ssid, true, false));
        hierarchicalRelevantProvider = new TreePathProviderAdapter(
                new EntityTypeIndexHierarchy(entityDefinitionService, ssid, true, false));
        flatAllProvider = new TreePathProviderAdapter(
                new EntityTypeIndexContentProvider(entityDefinitionService, ssid, false, false));
        hierarchicalAllProvider = new TreePathProviderAdapter(
                new EntityTypeIndexHierarchy(entityDefinitionService, ssid, false, false));
        viewer.setContentProvider(flatRelevantProvider);

        SchemaService ss = (SchemaService) PlatformUI.getWorkbench().getService(SchemaService.class);
        viewer.setInput(ss.getSchemas(ssid));
    }

    if (initialSelection != null) {
        viewer.setSelection(new StructuredSelection(initialSelection));
    }
}

From source file:eu.esdihumboldt.hale.ui.function.common.TypeEntityDialog.java

License:Open Source License

/**
 * @see EntityDialog#setupViewer(TreeViewer, EntityDefinition)
 *///www . j a v a 2  s.  co  m
@Override
protected void setupViewer(TreeViewer viewer, EntityDefinition initialSelection) {
    viewer.setLabelProvider(new StyledDefinitionLabelProvider());
    EntityDefinitionService entityDefinitionService = (EntityDefinitionService) PlatformUI.getWorkbench()
            .getService(EntityDefinitionService.class);

    flatRelevantProvider = new TreePathProviderAdapter(
            new EntityTypeIndexContentProvider(entityDefinitionService, ssid, true, true));
    if (!onlyMappingRelevant) {
        hierarchicalRelevantProvider = new TreePathProviderAdapter(
                new EntityTypeIndexHierarchy(entityDefinitionService, ssid, true, true));
        flatAllProvider = new TreePathProviderAdapter(
                new EntityTypeIndexContentProvider(entityDefinitionService, ssid, false, true));
        hierarchicalAllProvider = new TreePathProviderAdapter(
                new EntityTypeIndexHierarchy(entityDefinitionService, ssid, false, true));

        viewer.setContentProvider(flatAllProvider);
    } else {
        viewer.setContentProvider(flatRelevantProvider);
    }

    SchemaService ss = (SchemaService) PlatformUI.getWorkbench().getService(SchemaService.class);

    viewer.setInput(ss.getSchemas(ssid));

    if (initialSelection instanceof TypeEntityDefinition) {
        viewer.setSelection(new StructuredSelection(initialSelection));
    }
}

From source file:eu.esdihumboldt.hale.ui.functions.groovy.internal.TypeStructureTray.java

License:Open Source License

@Override
protected Control createContents(Composite parent) {
    Composite page = new Composite(parent, SWT.NONE);

    GridLayoutFactory.fillDefaults().numColumns(1).applyTo(page);

    // retrieve the types
    final Collection<? extends TypeDefinition> types = this.types.getTypes();

    // heading/*from   ww  w. j a  v  a  2s  . c  om*/
    Label caption = new Label(page, SWT.NONE);
    switch (schemaSpace) {
    case SOURCE:
        caption.setText("Source structure");
        break;
    case TARGET:
        caption.setText("Target structure");
        break;
    }
    caption.setFont(JFaceResources.getHeaderFont());

    // create tree viewer
    PatternFilter patternFilter = new SchemaPatternFilter();
    patternFilter.setIncludeLeadingWildcard(true);
    final FilteredTree filteredTree = new TreePathFilteredTree(page,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER, patternFilter, true);

    TreeViewer tree = filteredTree.getViewer();
    tree.setUseHashlookup(true);
    StyledDefinitionLabelProvider labelProvider = new StyledDefinitionLabelProvider();
    tree.setLabelProvider(labelProvider);
    IContentProvider contentProvider;
    if (types.size() == 1) {
        contentProvider = new TreePathProviderAdapter(new TypePropertyContentProvider(tree));
    } else {
        contentProvider = new TreePathProviderAdapter(new TypeDefinitionContentProvider(tree));
    }
    tree.setContentProvider(contentProvider);
    GridDataFactory.fillDefaults().grab(true, true).hint(280, 400).applyTo(filteredTree);

    tree.setComparator(new DefinitionComparator());

    // set input
    if (types.size() == 1) {
        tree.setInput(types.iterator().next());
    } else {
        tree.setInput(types);
    }

    /*
     * Groovy specific part
     */

    // caption
    Label example = new Label(page, SWT.NONE);
    switch (schemaSpace) {
    case SOURCE:
        example.setText("Examples: Access variables");
        break;
    case TARGET:
        example.setText("Example: Build instance");
        break;
    default:
        example.setText("Example");
    }

    // source viewer
    final SourceViewer viewer = new SourceViewer(page, null,
            SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY);

    final IColorManager colorManager = new GroovyColorManager();
    SourceViewerConfiguration configuration = new SimpleGroovySourceViewerConfiguration(colorManager,
            ImmutableList.of(BINDING_TARGET, BINDING_BUILDER, BINDING_INDEX, BINDING_SOURCE,
                    BINDING_SOURCE_TYPES, BINDING_TARGET_TYPE, BINDING_CELL, BINDING_LOG, BINDING_CELL_CONTEXT,
                    BINDING_FUNCTION_CONTEXT, BINDING_TRANSFORMATION_CONTEXT),
            null);
    viewer.configure(configuration);

    GridDataFactory.fillDefaults().grab(true, false).hint(200, 130).applyTo(viewer.getControl());

    // make sure the color manager is disposed
    viewer.getControl().addDisposeListener(new DisposeListener() {

        @Override
        public void widgetDisposed(DisposeEvent e) {
            colorManager.dispose();
        }
    });

    // react to tree selection changes
    tree.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IDocument doc = new Document();
            GroovySourceViewerUtil.setupDocument(doc);
            String example = null;
            if (!event.getSelection().isEmpty()) {
                switch (schemaSpace) {
                case SOURCE:
                    example = createSourceSample(event.getSelection(), types);
                    break;
                case TARGET:
                    example = createTargetSample(event.getSelection(), types);
                    break;
                }
            }

            if (example == null || example.isEmpty()) {
                switch (schemaSpace) {
                case SOURCE:
                    doc.set("// Please select schema elements to access");
                    break;
                case TARGET:
                    doc.set("// Please select which schema elements\n// to include in the instance to build");
                    break;
                default:
                    doc.set("// Please select one or more schema elements");
                }
            } else {
                doc.set(example);
            }

            viewer.setDocument(doc);
        }
    });

    tree.setSelection(StructuredSelection.EMPTY);

    return page;
}