Example usage for org.eclipse.jface.preference IPreferenceNode add

List of usage examples for org.eclipse.jface.preference IPreferenceNode add

Introduction

In this page you can find the example usage for org.eclipse.jface.preference IPreferenceNode add.

Prototype

public void add(IPreferenceNode node);

Source Link

Document

Adds the given preference node as a subnode of this preference node.

Usage

From source file:au.gov.ga.earthsci.application.preferences.PreferenceUtil.java

License:Apache License

/**
 * Populate the provided preference manager with nodes from the provided list of preference elements.
 * /*ww w  .  j  a va 2 s . c  o  m*/
 * @param pm The preference manager to populate
 * @param preferenceElements The list of preference elements from which to populate the manager
 * @param context The current eclipse context for DI etc.
 */
private static void populatePreferenceManager(PreferenceManager pm, IEclipseContext context,
        List<IConfigurationElement> preferenceElements) {
    // Add nodes in 3 phases:
    // 1. Add all root nodes (no category specified)
    // 2. Progressively add child nodes to build up the node tree, breadth first
    // 3. Add remaining (orphan) child nodes, along with a warning

    // Add root nodes
    int maxPathLength = 0;
    List<IConfigurationElement> remainingElements = new ArrayList<IConfigurationElement>();
    for (IConfigurationElement elmt : preferenceElements) {
        if (isEmpty(elmt.getAttribute(ATTR_CATEGORY))) {
            IPreferenceNode node = createPreferenceNode(elmt, context);
            if (node == null) {
                continue;
            }
            pm.addToRoot(node);
        } else {
            int categoryPathLength = elmt.getAttribute(ATTR_CATEGORY).split("\\\\").length; //$NON-NLS-1$
            maxPathLength = Math.max(maxPathLength, categoryPathLength);
            remainingElements.add(elmt);
        }
    }

    // Add child nodes
    preferenceElements = remainingElements;
    for (int i = 0; i < maxPathLength; i++) {
        remainingElements = new ArrayList<IConfigurationElement>();
        for (IConfigurationElement elmt : preferenceElements) {
            IPreferenceNode parent = findNode(pm, elmt.getAttribute(ATTR_CATEGORY));
            if (parent != null) {
                IPreferenceNode node = createPreferenceNode(elmt, context);
                parent.add(node);
            } else {
                remainingElements.add(elmt);
            }
        }
        preferenceElements = remainingElements;
    }

    // Finally, add any nodes that are parent-less, along with a warning
    for (IConfigurationElement elmt : preferenceElements) {
        logger.warn("Preference page {0} expected category {1} but none was found.", elmt.getAttribute(ATTR_ID), //$NON-NLS-1$
                elmt.getAttribute(ATTR_CATEGORY));
        IPreferenceNode node = createPreferenceNode(elmt, context);
        if (node == null) {
            continue;
        }
        pm.addToRoot(node);
    }
}

From source file:com.elphel.vdt.ui.options.SetupOptionsManager.java

License:Open Source License

private IPreferenceNode createPackageInstallNode(PackageContext context) {
    ImageDescriptor image = VDTPluginImages.getImageDescriptor(context);
    if (image == null)
        image = VDTPluginImages.DESC_PACKAGE_PROPERTIES;
    String page_id = PAGE_INSTALL_ID + ".Package." + context.getName();
    IPreferenceNode node = new PackageInstallNode(page_id, image, context);
    for (Tool tool : ToolsCore.getTools(context))
        node.add(createToolInstallNode(tool));

    return node;//from w w w .j  a v a2  s .c  o m
}

From source file:com.nsn.squirrel.preferences.internal.E4PreferenceRegistry.java

License:Open Source License

public PreferenceManager getPreferenceManager() {

    // Remember of the unbounded nodes to order parent pages.
    // Map<category, list of children> (all nodes except root nodes)
    Map<String, Collection<IPreferenceNode>> childrenNodes = new HashMap<String, Collection<IPreferenceNode>>();
    if (pm != null)
        return pm;
    pm = new PreferenceManager();
    IContributionFactory factory = context.get(IContributionFactory.class);
    for (IConfigurationElement elmt : registry.getConfigurationElementsFor(PREFS_PAGE_XP)) {
        String bundleId = elmt.getNamespaceIdentifier();
        if (!elmt.getName().equals(ELMT_PAGE)) {
            logger.warn("unexpected element: {0}", elmt.getName());
            continue;
        } else if (isEmpty(elmt.getAttribute(ATTR_ID)) || isEmpty(elmt.getAttribute(ATTR_NAME))) {
            logger.warn("missing id and/or name: {}", bundleId);
            continue;
        }/* ww w  .j  a  va  2s. co m*/
        PreferenceNode pn = null;
        if (elmt.getAttribute(ATTR_CLASS) != null) {
            PreferencePage page = null;
            try {
                String prefPageURI = getClassURI(bundleId, elmt.getAttribute(ATTR_CLASS));
                Object object = factory.create(prefPageURI, context);
                if (!(object instanceof PreferencePage)) {
                    logger.error("Expected instance of PreferencePage: {0}", elmt.getAttribute(ATTR_CLASS));
                    continue;
                }
                page = (PreferencePage) object;
                setPreferenceStore(bundleId, page);
            } catch (ClassNotFoundException e) {
                logger.error(e);
                continue;
            }
            ContextInjectionFactory.inject(page, context);
            if ((page.getTitle() == null || page.getTitle().isEmpty())
                    && elmt.getAttribute(ATTR_NAME) != null) {
                page.setTitle(elmt.getAttribute(ATTR_NAME));
            }
            pn = new PreferenceNode(elmt.getAttribute(ATTR_ID), page);
        } else {
            pn = new PreferenceNode(elmt.getAttribute(ATTR_ID),
                    new EmptyPreferencePage(elmt.getAttribute(ATTR_NAME)));
        }
        // Issue 2 : Fix bug on order (see :
        // https://github.com/opcoach/e4Preferences/issues/2)
        // Add only pages at root level and remember of child pages for
        // categories
        String category = elmt.getAttribute(ATTR_CATEGORY);
        if (isEmpty(category)) {
            pm.addToRoot(pn);
        } else {
            /*
             * IPreferenceNode parent = findNode(pm, category); if (parent
             * == null) { // No parent found, but may be the extension has
             * not been read yet. So remember of it unboundedNodes.put(pn,
             * category); } else { parent.add(pn); }
             */
            // Check if this category is already registered.
            Collection<IPreferenceNode> children = childrenNodes.get(category);
            if (children == null) {
                children = new ArrayList<IPreferenceNode>();
                childrenNodes.put(category, children);
            }
            children.add(pn);
        }
    }
    // Must now bind pages that has not been added in nodes (depends on the
    // preference page read order)
    // Iterate on all possible categories
    Collection<String> categoriesDone = new ArrayList<String>();
    while (!childrenNodes.isEmpty()) {
        for (String cat : Collections.unmodifiableSet(childrenNodes.keySet())) {
            // Is this category already in preference manager ? If not add
            // it later...
            IPreferenceNode parent = findNode(pm, cat);
            if (parent != null) {
                // Can add the list of children to this parent page...
                for (IPreferenceNode pn : childrenNodes.get(cat)) {
                    parent.add(pn);
                }
                // Ok This parent page is done. Can remove it from map
                // outside of this loop
                categoriesDone.add(cat);
            }
        }
        for (String keyToRemove : categoriesDone)
            childrenNodes.remove(keyToRemove);
        categoriesDone.clear();
    }
    return pm;
}

From source file:com.opcoach.e4.preferences.internal.E4PreferenceRegistry.java

License:Open Source License

public PreferenceManager getPreferenceManager() {

    // Remember of the unbounded nodes to order parent pages.
    // Map<category, list of children> (all nodes except root nodes)
    Map<String, Collection<IPreferenceNode>> childrenNodes = new HashMap<String, Collection<IPreferenceNode>>();

    if (pm != null)
        return pm;

    pm = new PreferenceManager();
    IContributionFactory factory = context.get(IContributionFactory.class);

    for (IConfigurationElement elmt : registry.getConfigurationElementsFor(PREFS_PAGE_XP)) {
        String bundleId = elmt.getNamespaceIdentifier();
        if (!elmt.getName().equals(ELMT_PAGE)) {
            logger.warn("unexpected element: {0}", elmt.getName());
            continue;
        } else if (isEmpty(elmt.getAttribute(ATTR_ID)) || isEmpty(elmt.getAttribute(ATTR_NAME))) {
            logger.warn("missing id and/or name: {}", bundleId);
            continue;
        }/*from  w  ww  .jav  a  2s.  c om*/
        PreferenceNode pn = null;
        if (elmt.getAttribute(ATTR_CLASS) != null) {
            PreferencePage page = null;
            try {
                String prefPageURI = getClassURI(bundleId, elmt.getAttribute(ATTR_CLASS));
                Object object = factory.create(prefPageURI, context);
                if (!(object instanceof PreferencePage)) {
                    logger.error("Expected instance of PreferencePage: {0}", elmt.getAttribute(ATTR_CLASS));
                    continue;
                }
                page = (PreferencePage) object;
                setPreferenceStore(bundleId, page);

            } catch (ClassNotFoundException e) {
                logger.error(e);
                continue;
            }
            ContextInjectionFactory.inject(page, context);
            if ((page.getTitle() == null || page.getTitle().isEmpty())
                    && elmt.getAttribute(ATTR_NAME) != null) {
                page.setTitle(elmt.getAttribute(ATTR_NAME));
            }

            pn = new PreferenceNode(elmt.getAttribute(ATTR_ID), page);
        } else {
            pn = new PreferenceNode(elmt.getAttribute(ATTR_ID),
                    new EmptyPreferencePage(elmt.getAttribute(ATTR_NAME)));
        }

        // Issue 2 : Fix bug on order (see :
        // https://github.com/opcoach/e4Preferences/issues/2)
        // Add only pages at root level and remember of child pages for
        // categories
        String category = elmt.getAttribute(ATTR_CATEGORY);
        if (isEmpty(category)) {
            pm.addToRoot(pn);
        } else {
            /*
             * IPreferenceNode parent = findNode(pm, category); if (parent
             * == null) { // No parent found, but may be the extension has
             * not been read yet. So remember of it unboundedNodes.put(pn,
             * category); } else { parent.add(pn); }
             */
            // Check if this category is already registered.
            Collection<IPreferenceNode> children = childrenNodes.get(category);
            if (children == null) {
                children = new ArrayList<IPreferenceNode>();
                childrenNodes.put(category, children);
            }
            children.add(pn);
        }
    }

    // Must now bind pages that has not been added in nodes (depends on the
    // preference page read order)
    // Iterate on all possible categories
    Collection<String> categoriesDone = new ArrayList<String>();

    while (!childrenNodes.isEmpty()) {
        for (String cat : Collections.unmodifiableSet(childrenNodes.keySet())) {
            // Is this category already in preference manager ? If not add
            // it later...
            IPreferenceNode parent = findNode(pm, cat);
            if (parent != null) {
                // Can add the list of children to this parent page...
                for (IPreferenceNode pn : childrenNodes.get(cat)) {
                    parent.add(pn);
                }
                // Ok This parent page is done. Can remove it from map
                // outside of this loop
                categoriesDone.add(cat);
            }
        }

        for (String keyToRemove : categoriesDone)
            childrenNodes.remove(keyToRemove);
        categoriesDone.clear();

    }

    return pm;
}

From source file:net.mldonkey.g2gui.view.pref.Preferences.java

License:Open Source License

/**
 * @param connected are we connected to the Core
 * @param mldonkey the Core were i get all my options from
 *///from  ww w  .j a v a2  s. co  m
private void createMLDonkeyOptions(CoreCommunication mldonkey) {
    OptionsInfoMap options = mldonkey.getOptionsInfoMap();
    OptionsPreferenceStore optionsStore = new OptionsPreferenceStore();
    optionsStore.setInput(options);

    Map sections = new HashMap();
    Map plugins = new HashMap();
    MLDonkeyOptions advanced = null;

    /*now we iterate over the whole thing and create the preferencePages*/
    Iterator it = options.keySet().iterator();

    while (it.hasNext()) {
        OptionsInfo option = (OptionsInfo) options.get(it.next());
        String section = option.getSectionToAppear();
        String plugin = option.getPluginToAppear();

        if ((section == null) && (plugin == null) && showOption(option)) {
            if (preferenceStore.getBoolean("advancedMode")) {
                if (advanced == null) {
                    advanced = new MLDonkeyOptions("Advanced ", FieldEditorPreferencePage.GRID);
                    advanced.setPreferenceStore(optionsStore);
                }

                advanced.addOption(option);
            }
        } else if ((section != null) && section.equalsIgnoreCase("other") && showOption(option)) {
            if (preferenceStore.getBoolean("advancedMode")) {
                if (advanced == null) {
                    advanced = new MLDonkeyOptions("Advanced ", FieldEditorPreferencePage.GRID);
                    advanced.setPreferenceStore(optionsStore);
                }

                advanced.addOption(option);
            }
        } else if ((section != null) && showOption(option)) {
            /* create the section, or if already done, only add the option */
            if (!sections.containsKey(section)) {
                MLDonkeyOptions temp = new MLDonkeyOptions(section, FieldEditorPreferencePage.GRID);

                //myprefs.addToRoot( new PreferenceNode ( section, temp ) );
                sections.put(section, temp);
                temp.setPreferenceStore(optionsStore);
            }

            ((MLDonkeyOptions) sections.get(section)).addOption(option);
        } else if ((plugin != null) && showOption(option)) {
            /* create the pluginSection, or if already done, only add the option */
            if (!plugins.containsKey(plugin)) {
                /*only create the plugin, if it is possible at all...*/
                MLDonkeyOptions temp = new MLDonkeyOptions(plugin, FieldEditorPreferencePage.GRID);
                plugins.put(plugin, temp);
                temp.setPreferenceStore(optionsStore);
            }

            ((MLDonkeyOptions) plugins.get(plugin)).addOption(option);
        }
    }

    /*Now we create the tree-structure, since we received all options*/
    /*
     * first the sections:
     */
    it = sections.keySet().iterator();

    while (it.hasNext()) {
        String key = (String) it.next();
        MLDonkeyOptions page = (MLDonkeyOptions) sections.get(key);
        addToRoot((new PreferenceNode(key, page)));
    }

    /*
     * and now the Plugins: first try to get the PrefPage "Networks", where all the "enabled"
     * options are, if this doesn't exist, create it. And then put all the plugins below this one
     */
    if (plugins.size() != 0) {
        IPreferenceNode pluginOptions = find("Networks");

        if (pluginOptions == null) {
            MLDonkeyOptions emptyItem = new MLDonkeyOptions("Networks", FieldEditorPreferencePage.FLAT);
            pluginOptions = new PreferenceNode("Networks", emptyItem);
            emptyItem.isEmpty(true);
            addToRoot(pluginOptions);
        }

        it = plugins.keySet().iterator();

        while (it.hasNext()) {
            String key = (String) it.next();
            MLDonkeyOptions page = (MLDonkeyOptions) plugins.get(key);
            pluginOptions.add((new PreferenceNode(key, page)));
        }
    }

    /*and now add the advanced-field at the very bottom of the list*/
    if (advanced != null)
        addToRoot((new PreferenceNode("Advanced", advanced)));
}

From source file:org.cs3.pdt.graphicalviews.focusview.ViewBase.java

License:Open Source License

protected void initButtons(final Composite parent) {
    IActionBars bars = this.getViewSite().getActionBars();
    IToolBarManager toolBarManager = bars.getToolBarManager();

    initViewButtons(toolBarManager);//www . ja  va 2  s  . com

    toolBarManager.add(new Separator("control"));

    toolBarManager
            .add(new ToolBarAction("Navigation", ImageRepository.getImageDescriptor(ImageRepository.MOVE)) {

                @Override
                public int getStyle() {
                    return IAction.AS_CHECK_BOX;
                }

                @Override
                public void performAction() {
                    navigationEnabled = !navigationEnabled;
                    focusViewCoordinator.currentFocusView.recalculateMode();
                }
            });

    toolBarManager.add(new ToolBarAction("Update", "WARNING: Current layout will be rearranged!",
            ImageRepository.getImageDescriptor(ImageRepository.REFRESH)) {

        @Override
        public void performAction() {
            updateCurrentFocusView();
        }
    });

    toolBarManager.add(new Separator("layout"));

    toolBarManager
            .add(new ToolBarAction("Hierarchical layout", org.cs3.pdt.graphicalviews.internal.ImageRepository
                    .getImageDescriptor(org.cs3.pdt.graphicalviews.internal.ImageRepository.HIERARCHY)) {

                @Override
                public void performAction() {
                    PredicateLayoutPreferences.setLayoutPreference(PreferenceConstants.LAYOUT_HIERARCHY);
                    updateCurrentFocusViewLayout();
                }
            });

    toolBarManager.add(new ToolBarAction("Organic layout", org.cs3.pdt.graphicalviews.internal.ImageRepository
            .getImageDescriptor(org.cs3.pdt.graphicalviews.internal.ImageRepository.ORGANIC)) {

        @Override
        public void performAction() {
            PredicateLayoutPreferences.setLayoutPreference(PreferenceConstants.LAYOUT_ORGANIC);
            updateCurrentFocusViewLayout();
        }
    });

    toolBarManager.add(new Separator("preferences"));

    toolBarManager.add(
            new ToolBarAction("Preferences", ImageRepository.getImageDescriptor(ImageRepository.PREFERENCES)) {

                @Override
                public void performAction() {
                    PreferenceManager globalmgr = PlatformUI.getWorkbench().getPreferenceManager();
                    IPreferenceNode node = globalmgr.find(
                            "org.cs3.pdt.common.internal.preferences.PDTCommonPreferencePage/org.cs3.pdt.graphicalviews.preferences.MainPreferencePage");

                    IPreferencePage page = new MainPreferencePage();
                    page.setTitle("Context View");
                    IPreferenceNode root = new PreferenceNode("PreferencePage", page);
                    root.add(node);

                    PreferenceManager mgr = new PreferenceManager('.', (PreferenceNode) root);

                    PreferenceDialog dialog = new PreferenceDialog(getSite().getShell(), mgr);
                    dialog.create();
                    dialog.setMessage(page.getTitle());
                    dialog.open();
                }
            });

    toolBarManager.add(new ToolBarAction("Help", ImageRepository.getImageDescriptor(ImageRepository.HELP)) {

        @Override
        public void performAction() {
            new HelpDialog(getSite().getShell()).open();
        }
    });

}

From source file:org.eclipse.cdt.embsysregview.views.EmbSysRegView.java

License:Open Source License

/**
 * This is a callback that creates the viewer and initialize it.
 *//* w w  w .  jav a 2 s.c om*/
public void createPartControl(final Composite parent) {
    Bundle bundle = Platform.getBundle("org.eclipse.cdt.embsysregview");
    URL fileURL = bundle.getEntry("icons/selected_register.png");
    URL fileURL2 = bundle.getEntry("icons/unselected_register.png");
    URL fileURL3 = bundle.getEntry("icons/selected_field.png");
    URL fileURL4 = bundle.getEntry("icons/unselected_field.png");
    URL fileURL5 = bundle.getEntry("icons/info.png");
    URL fileURL6 = bundle.getEntry("icons/interpretation.png");
    URL fileURL7 = bundle.getEntry("icons/config.png");

    try {
        selectedImage = new Image(parent.getDisplay(), fileURL.openStream());
        unselectedImage = new Image(parent.getDisplay(), fileURL2.openStream());
        selectedFieldImage = new Image(parent.getDisplay(), fileURL3.openStream());
        unselectedFieldImage = new Image(parent.getDisplay(), fileURL4.openStream());
        infoImage = new Image(parent.getDisplay(), fileURL5.openStream());
        interpretationImage = new Image(parent.getDisplay(), fileURL6.openStream());
        configButtonImage = new Image(parent.getDisplay(), fileURL7.openStream());
    } catch (Exception e) {
        selectedImage = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_DEC_FIELD_ERROR);
        unselectedImage = PlatformUI.getWorkbench().getSharedImages()
                .getImage(ISharedImages.IMG_DEC_FIELD_ERROR);
        selectedFieldImage = PlatformUI.getWorkbench().getSharedImages()
                .getImage(ISharedImages.IMG_DEC_FIELD_ERROR);
        unselectedFieldImage = PlatformUI.getWorkbench().getSharedImages()
                .getImage(ISharedImages.IMG_DEC_FIELD_ERROR);
        infoImage = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_DEC_FIELD_ERROR);
        interpretationImage = PlatformUI.getWorkbench().getSharedImages()
                .getImage(ISharedImages.IMG_DEC_FIELD_ERROR);
        configButtonImage = PlatformUI.getWorkbench().getSharedImages()
                .getImage(ISharedImages.IMG_DEC_FIELD_ERROR);
    }

    TreeViewerColumn column;
    parent.setLayout(new MigLayout("fill", "", ""));

    header = new Composite(parent, SWT.NONE);
    /*header.setLayout(new MigLayout("fill","",""));*/
    header.setLayoutData("dock north,height 16px,width 100%,wmin 0,hmin 16,gap 0 0 -5 0");
    RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);

    rowLayout.marginLeft = -1;
    rowLayout.marginRight = 0;
    rowLayout.marginTop = -1;
    rowLayout.marginBottom = 0;
    rowLayout.fill = true;
    rowLayout.wrap = false;
    rowLayout.spacing = 5;
    header.setLayout(rowLayout);

    configButton = new Button(header, SWT.FLAT);
    configButton.setImage(configButtonImage);
    configButton.setSize(17, 17);
    RowData data = new RowData();
    data.width = 17;
    data.height = 17;
    configButton.setLayoutData(data);
    configButton.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            if (e.type == SWT.Selection) {
                IPreferencePage page = new PreferencePageEmbSys();
                page.setTitle("EmbSysRegView");
                IPreferencePage page2 = new PreferencePageEmbSysBehavior();
                page2.setTitle("Behavior");
                PreferenceManager mgr = new PreferenceManager();
                IPreferenceNode node = new PreferenceNode("1", page);
                node.add(new PreferenceNode("2", page2));
                mgr.addToRoot(node);
                PreferenceDialog dialog = new PreferenceDialog(
                        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), mgr);
                dialog.create();
                dialog.setMessage(page.getTitle());
                dialog.open();
            }
        }
    });

    collapseButton = new Button(header, SWT.FLAT);
    collapseButton.setLayoutData(new RowData(17, 17));
    collapseButton
            .setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_ELCL_COLLAPSEALL));
    collapseButton.setToolTipText("Collapse all open tree nodes");
    collapseButton.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            if (e.type == SWT.Selection) {
                viewer.collapseAll();
            }
        }
    });

    activateAllButton = new Button(header, SWT.FLAT);
    activateAllButton.setLayoutData(new RowData(17, 17));
    activateAllButton.setText("*"); // Not very clear, should/could be some custom graphics featuring the color green, perhaps?
    activateAllButton.setToolTipText(
            "Activate all registers (or none, if Control is pressed); press Shift to only affect visible registers");
    activateAllButton.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            if (e.type == SWT.Selection) {
                activateAll((e.stateMask & SWT.CONTROL) == 0, (e.stateMask & SWT.SHIFT) != 0);
            }
        }
    });

    copyButton = new Button(header, SWT.FLAT);
    copyButton.setLayoutData(new RowData(17, 17));
    copyButton.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_COPY));
    copyButton.setToolTipText("Copy active (green) register values to clipboard");
    copyButton.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            if (e.type == SWT.Selection) {
                final StringBuilder sb = new StringBuilder();
                copyRegisters(sb);
                if (sb.length() > 0) {
                    final Clipboard cb = new Clipboard(Display.getCurrent());
                    final TextTransfer tt = TextTransfer.getInstance();
                    cb.setContents(new Object[] { sb.toString() }, new Transfer[] { tt });
                }
            }
        }
    });

    infoLabel = new Label(header, SWT.NONE);

    viewer = new TreeViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
    viewer.getControl().setLayoutData("height 100%,width 100%,hmin 0,wmin 0");
    viewer.getTree().setLinesVisible(true);
    viewer.getTree().setHeaderVisible(true);

    // Registername
    column = new TreeViewerColumn(viewer, SWT.NONE);
    column.getColumn().setWidth(250);
    column.getColumn().setMoveable(false);
    column.getColumn().setText("Register");
    column.setLabelProvider(new ColumnLabelProvider() {

        @Override
        public Color getForeground(Object element) {
            if (element instanceof TreeRegister)
                if (((TreeRegister) element).isRetrievalActive())
                    return parent.getShell().getDisplay().getSystemColor(SWT.COLOR_DARK_GREEN);
            if (element instanceof TreeField)
                if (((TreeRegister) ((TreeField) element).getParent()).isRetrievalActive())
                    return parent.getShell().getDisplay().getSystemColor(SWT.COLOR_DARK_GREEN);

            return null;
        }

        public String getText(Object element) {
            if (element instanceof TreeField) {
                final int bitOffset = ((TreeField) element).getBitOffset();
                final int bitLength = ((TreeField) element).getBitLength();

                if (bitLength == 1)
                    return element.toString() + " (bit " + String.valueOf(bitOffset) + ")";
                else
                    return element.toString() + " (bits " + String.valueOf(bitOffset + bitLength - 1) + "-"
                            + String.valueOf(bitOffset) + ")";
            } else
                return element.toString();
        }

        public Image getImage(Object obj) {
            if (obj instanceof TreeParent) {
                if (obj instanceof TreeRegister)
                    if (((TreeRegister) obj).isRetrievalActive())
                        return selectedImage;
                    else
                        return unselectedImage;
            }
            if (obj instanceof TreeField) {
                if (((TreeRegister) ((TreeField) obj).getParent()).isRetrievalActive())
                    return selectedFieldImage;
                else
                    return unselectedFieldImage;
            }
            return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
        }

    });

    // Hex Value
    column = new TreeViewerColumn(viewer, SWT.NONE);
    column.getColumn().setWidth(80);
    column.getColumn().setMoveable(false);
    column.getColumn().setText("Hex");
    column.setLabelProvider(new ColumnLabelProvider() {
        @Override
        public Color getForeground(Object element) {
            if (element instanceof TreeRegister)
                if (!((TreeRegister) element).isWriteOnly())
                    if (((TreeRegister) element).hasValueChanged())
                        return parent.getShell().getDisplay().getSystemColor(SWT.COLOR_RED);
            if (element instanceof TreeField)
                if (!((TreeRegister) ((TreeField) element).getParent()).isWriteOnly())
                    if (((TreeField) element).hasValueChanged())
                        return parent.getShell().getDisplay().getSystemColor(SWT.COLOR_RED);
            return null;
        }

        public String getText(Object element) {
            if (element instanceof TreeGroup)
                return "";
            if (element instanceof TreeRegisterGroup)
                return "";
            if (element instanceof TreeRegister)
                if (((TreeRegister) element).getValue() == -1)
                    return "";
                else if (((TreeRegister) element).isWriteOnly())
                    return "- write only -";
                else
                    return Utils.longtoHexString(((TreeRegister) element).getValue(),
                            ((TreeRegister) element).getBitSize());
            if (element instanceof TreeField)
                if (((TreeRegister) ((TreeField) element).getParent()).getValue() == -1)
                    return "";
                else if (((TreeRegister) ((TreeField) element).getParent()).isWriteOnly())
                    return "- write only -";
                else
                    return Utils.longtoHexString(((TreeField) element).getValue(),
                            ((TreeField) element).getBitLength());
            else
                return element.toString();
        }

    });

    final TextCellEditor textCellEditor = new TextCellEditor(viewer.getTree());
    textCellEditor.setValidator(new HexCellEditorValidator(viewer));
    final ComboBoxCellEditor comboBoxCellEditor = new ComboBoxCellEditor(viewer.getTree(), new String[0],
            SWT.NONE);

    comboBoxCellEditor.setValidator(new HexCellEditorValidator(viewer));

    ((CCombo) comboBoxCellEditor.getControl()).addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            int selectionIndex = ((CCombo) comboBoxCellEditor.getControl()).getSelectionIndex();

            TreeElement obj = currentEditedElement;
            if (obj instanceof TreeField) {
                long value = -1;

                if (selectionIndex != -1) {
                    value = ((TreeField) obj).getInterpretations()
                            .getValue(((CCombo) comboBoxCellEditor.getControl()).getItem(selectionIndex));
                } else {
                    String svalue = ((CCombo) comboBoxCellEditor.getControl()).getText();
                    if (svalue.startsWith("0x"))
                        value = Long.valueOf(svalue.substring(2, svalue.length()), 16);

                }
                if (value != -1)
                    ((TreeField) obj).setValue(value);

            }

            if (((TreeRegister) obj.getParent()).isWriteOnly())
                updateTreeFields(invisibleRoot);
            viewer.refresh();

        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
    comboBoxCellEditor.addListener(new ICellEditorListener() {

        @Override
        public void applyEditorValue() {
            int selectionIndex = ((CCombo) comboBoxCellEditor.getControl()).getSelectionIndex();

            TreeElement obj = currentEditedElement;
            if (obj instanceof TreeField) {
                long value = -1;

                if (selectionIndex != -1) {
                    value = ((TreeField) obj).getInterpretations()
                            .getValue(((CCombo) comboBoxCellEditor.getControl()).getItem(selectionIndex));
                } else {
                    String svalue = ((CCombo) comboBoxCellEditor.getControl()).getText();
                    if (svalue.startsWith("0x"))
                        value = Long.valueOf(svalue.substring(2, svalue.length()), 16);

                }
                if (value != -1)
                    ((TreeField) obj).setValue(value);

            }

            if (((TreeRegister) obj.getParent()).isWriteOnly())
                updateTreeFields(invisibleRoot);
            viewer.refresh();
        }

        @Override
        public void cancelEditor() {
        }

        @Override
        public void editorValueChanged(boolean oldValidState, boolean newValidState) {
        }
    });

    column.setEditingSupport(new EditingSupport(viewer) {
        @Override
        protected boolean canEdit(Object element) {
            if (element instanceof TreeField
                    && ((((TreeRegister) ((TreeField) element).getParent()).isReadWrite())
                            || (((TreeRegister) ((TreeField) element).getParent()).isWriteOnly())))
                return true;
            if (element instanceof TreeRegister
                    && (((TreeRegister) element).isReadWrite() || ((TreeRegister) element).isWriteOnly()))
                return true;
            return false;
        }

        @Override
        protected CellEditor getCellEditor(Object element) {
            if (element instanceof TreeField && ((TreeField) element).hasInterpretations()) {
                comboBoxCellEditor.setItems(((TreeField) element).getInterpretations().getInterpretations());
                IPreferenceStore store = Activator.getDefault().getPreferenceStore();
                int store_combolength = store.getInt("combolength");
                if (store_combolength > 0)
                    ((CCombo) comboBoxCellEditor.getControl()).setVisibleItemCount(store_combolength);
                currentEditedElement = (TreeElement) element;
                return comboBoxCellEditor;
            } else
                return textCellEditor;
        }

        @Override
        protected Object getValue(Object element) {
            if (element instanceof TreeField && ((TreeField) element).hasInterpretations()) {
                // TODO: check if the Integer is for index in the combobox
                return new Integer((int) ((TreeField) element).getValue()); // TODO: what to do on large bitfield ?
            } else {
                if (element instanceof TreeField && ((TreeField) element).getValue() != -1)
                    return Utils.longtoHexString(((TreeField) element).getValue(),
                            ((TreeField) element).getBitLength());

                if (element instanceof TreeRegister && ((TreeRegister) element).getValue() != -1)
                    return Utils.longtoHexString(((TreeRegister) element).getValue(),
                            ((TreeRegister) element).getBitSize());
            }
            return null;
        }

        @Override
        protected void setValue(Object element, Object value) {
            if (value == null)
                return;
            if (value instanceof String) {
                if (element instanceof TreeRegister && ((String) value).startsWith("0x")) {
                    String svalue = ((String) value);
                    long lvalue = Long.valueOf(svalue.substring(2, svalue.length()), 16);

                    TreeRegister treeRegister = ((TreeRegister) element);
                    if (treeRegister.getValue() != -1 && treeRegister.getValue() != lvalue) {
                        // Update Value on device
                        treeRegister.setAndWriteValue(lvalue);
                        if (((TreeRegister) element).isWriteOnly())
                            updateTreeFields(invisibleRoot);
                        viewer.refresh();
                    }
                }

                if (element instanceof TreeField && ((String) value).startsWith("0x")) {
                    String svalue = ((String) value);
                    long fvalue = Long.valueOf(svalue.substring(2, svalue.length()), 16);

                    TreeField treeField = ((TreeField) element);
                    if (treeField.getValue() != -1 && treeField.getValue() != fvalue) {
                        TreeRegister treeRegister = ((TreeRegister) treeField.getParent());

                        // calculate register value + modified field to write into register
                        long rvalue = treeRegister.getValue();
                        int bitLength = treeField.getBitLength();
                        int bitOffset = treeField.getBitOffset();
                        long mask;

                        mask = (0xFFFFFFFFL >> (32 - bitLength)) << bitOffset;
                        rvalue = rvalue & (~mask); // clear field bits in register value
                        fvalue = fvalue << bitOffset; // shift field value into its position in the register
                        fvalue = fvalue & mask; // just to be sure, cut everything but the field
                        rvalue = rvalue | fvalue; // blend the field value into the register value

                        // Update Value in Target
                        treeRegister.setAndWriteValue(rvalue);
                        if (((TreeRegister) (((TreeField) element).getParent())).isWriteOnly())
                            updateTreeFields(invisibleRoot);
                        viewer.refresh(treeRegister);
                    }
                }
            }
            //TODO: why...what for...
            //viewer.refresh(element);
        }
    });

    // Binary Value
    column = new TreeViewerColumn(viewer, SWT.NONE);
    column.getColumn().setWidth(200);
    column.getColumn().setMoveable(false);
    column.getColumn().setText("Bin");
    column.setLabelProvider(new ColumnLabelProvider() {
        @Override
        public Color getForeground(Object element) {
            if (element instanceof TreeRegister)
                if (!((TreeRegister) element).isWriteOnly())
                    if (((TreeRegister) element).hasValueChanged())
                        return parent.getShell().getDisplay().getSystemColor(SWT.COLOR_RED);
            if (element instanceof TreeField)
                if (!((TreeRegister) ((TreeField) element).getParent()).isWriteOnly())
                    if (((TreeField) element).hasValueChanged())
                        return parent.getShell().getDisplay().getSystemColor(SWT.COLOR_RED);

            return null;
        }

        public String getText(Object element) {
            if (element instanceof TreeGroup)
                return "";
            if (element instanceof TreeRegisterGroup)
                return "";
            if (element instanceof TreeRegister)
                if (((TreeRegister) element).getValue() == -1)
                    return "";
                else if (((TreeRegister) element).isWriteOnly())
                    return "------------- write only -------------";
                else
                    return Utils.longtobinarystring(((TreeRegister) element).getValue(),
                            ((TreeRegister) element).getBitSize());
            if (element instanceof TreeField)
                if (((TreeRegister) ((TreeField) element).getParent()).getValue() == -1)
                    return "";
                else if (((TreeRegister) ((TreeField) element).getParent()).isWriteOnly())
                    return "------------- write only -------------";
                else
                    return Utils.longtobinarystring(((TreeField) element).getValue(),
                            ((TreeField) element).getBitLength());
            else
                return element.toString();
        }

    });

    column.setEditingSupport(new EditingSupport(viewer) {
        @Override
        protected boolean canEdit(Object element) {
            if (element instanceof TreeField
                    && ((((TreeRegister) ((TreeField) element).getParent()).isReadWrite())
                            || (((TreeRegister) ((TreeField) element).getParent()).isWriteOnly())))
                return true;
            if (element instanceof TreeRegister
                    && (((TreeRegister) element).isReadWrite() || ((TreeRegister) element).isWriteOnly()))
                return true;
            return false;
        }

        @Override
        protected CellEditor getCellEditor(Object element) {
            return new BinaryButtonsCellEditor(viewer.getTree(), viewer);
        }

        @Override
        protected Object getValue(Object element) {
            return element;
        }

        @Override
        protected void setValue(Object element, Object value) {
            viewer.refresh(element);
        }
    });

    // Register Reset Value (hex)
    column = new TreeViewerColumn(viewer, SWT.NONE);
    column.getColumn().setWidth(80);
    column.getColumn().setMoveable(false);
    column.getColumn().setText("Reset");
    column.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            if (element instanceof TreeGroup)
                return "";
            if (element instanceof TreeRegisterGroup)
                return "";
            if (element instanceof TreeRegister)
                return Utils.longtoHexString(((TreeRegister) element).getResetValue(),
                        ((TreeRegister) element).getBitSize());
            if (element instanceof TreeField)
                return "";
            else
                return "";
        }

    });

    // Register Access
    column = new TreeViewerColumn(viewer, SWT.NONE);
    column.getColumn().setAlignment(SWT.CENTER);
    column.getColumn().setWidth(50);
    column.getColumn().setMoveable(false);
    column.getColumn().setText("Access");
    column.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            if (element instanceof TreeGroup)
                return "";
            if (element instanceof TreeRegisterGroup)
                return "";
            if (element instanceof TreeRegister)
                return ((TreeRegister) element).getType().toUpperCase();
            if (element instanceof TreeField)
                return "";
            else
                return "";
        }

    });

    // Register Address (hex)
    column = new TreeViewerColumn(viewer, SWT.NONE);
    column.getColumn().setWidth(80);
    column.getColumn().setMoveable(false);
    column.getColumn().setText("Address");
    column.setLabelProvider(new ColumnLabelProvider() {
        public String getText(Object element) {
            if (element instanceof TreeGroup)
                return "";
            if (element instanceof TreeRegisterGroup)
                return "";
            if (element instanceof TreeRegister)
                return Utils.longtoHexString(((TreeRegister) element).getRegisterAddress(), 32); //TODO: get address width from xml ...
            if (element instanceof TreeField)
                return "";
            else
                return "";
        }

    });

    // Description
    column = new TreeViewerColumn(viewer, SWT.NONE);
    column.getColumn().setWidth(300);
    column.getColumn().setMoveable(false);
    column.getColumn().setText("Description");
    ColumnViewerToolTipSupport.enableFor(viewer);

    column.setLabelProvider(new CellLabelProvider() {

        public String getToolTipText(Object element) {
            if (element instanceof TreeRegister) { // only display if more than one line is found
                if (org.eclipse.cdt.embsysregview.views.Utils
                        .countTextLines(((TreeRegister) element).getDescription()) > 1)
                    return ((TreeRegister) element).getDescription();
                else
                    return null;
            }
            if (element instanceof TreeField) { // display tooltip if more than one line is found, or an interpretation is shown instead of this one line
                if (org.eclipse.cdt.embsysregview.views.Utils
                        .countTextLines(((TreeField) element).getDescription()) > 1
                        || ((TreeField) element).hasInterpretation())
                    return ((TreeField) element).getDescription();
                else
                    return null;
            }
            return null;
        }

        public Point getToolTipShift(Object object) {
            return new Point(5, 5);
        }

        public int getToolTipDisplayDelayTime(Object object) {
            return 200;
        }

        public int getToolTipTimeDisplayed(Object object) {
            return 0;
        }

        public void update(ViewerCell cell) {
            Object element = cell.getElement();
            if (element instanceof TreeGroup)
                cell.setText(((TreeGroup) element).getDescription());
            if (element instanceof TreeRegisterGroup)
                cell.setText(((TreeRegisterGroup) element).getDescription());
            if (element instanceof TreeRegister) {
                cell.setText(org.eclipse.cdt.embsysregview.views.Utils
                        .getFirstNotEmptyTextLine(((TreeRegister) element).getDescription()).trim());
            }

            if (element instanceof TreeField)
                if (((TreeField) element).hasInterpretation()) {
                    cell.setText(((TreeField) element).getInterpretation());
                    cell.setImage(interpretationImage);
                } else {
                    // Display first line
                    cell.setText(org.eclipse.cdt.embsysregview.views.Utils
                            .getFirstNotEmptyTextLine(((TreeField) element).getDescription()).trim());
                    // Display Icon if there are more than one line
                    if (org.eclipse.cdt.embsysregview.views.Utils
                            .countTextLines(((TreeField) element).getDescription()) > 1)
                        cell.setImage(infoImage);
                }
        }
    });

    doubleClickAction = new Action() {
        public void run() {
            ISelection selection = viewer.getSelection();

            Object obj = ((IStructuredSelection) selection).getFirstElement();

            int selectedColumn = -1;

            Tree tree = viewer.getTree();
            Point pt = tree.toControl(Display.getCurrent().getCursorLocation());
            viewer.getTree().getColumnCount();
            for (int i = 0; i < tree.getColumnCount(); i++) {
                TreeItem item = tree.getItem(pt);
                if (item != null) {
                    if (item.getBounds(i).contains(pt)) {
                        selectedColumn = i;
                    }
                }
            }

            if (obj instanceof TreeRegisterGroup && selectedColumn == 0) {
                TreeRegisterGroup treeRegisterGroup = ((TreeRegisterGroup) obj);
                TreeElement[] treeElements = treeRegisterGroup.getChildren();
                for (TreeElement treeElement : treeElements) {
                    TreeRegister treeRegister = ((TreeRegister) treeElement);
                    if (!treeRegister.isWriteOnly()) {
                        treeRegister.toggleRetrieval();
                        treeRegister.readValue();
                    }
                }
                viewer.refresh(obj);
            }

            if (obj instanceof TreeRegister && selectedColumn == 0) {
                TreeRegister treeRegister = ((TreeRegister) obj);
                if (!treeRegister.isWriteOnly()) {
                    treeRegister.toggleRetrieval();
                    treeRegister.readValue();
                    viewer.refresh(obj);
                }
            }
            if (obj instanceof TreeField && selectedColumn == 0) {
                TreeField treeField = ((TreeField) obj);
                TreeRegister treeRegister = ((TreeRegister) treeField.getParent());
                if (!treeRegister.isWriteOnly()) {
                    treeRegister.toggleRetrieval();
                    treeRegister.readValue();
                    viewer.refresh(treeField.getParent());
                }
            }
        }
    };

    viewer.addDoubleClickListener(new IDoubleClickListener() {
        public void doubleClick(DoubleClickEvent event) {
            doubleClickAction.run();
        }
    });

    viewer.setContentProvider(new ViewContentProvider());
    updateInfoLabel();
    viewer.setInput(invisibleRoot);
}

From source file:org.eclipse.help.ui.internal.views.ScopePreferenceManager.java

License:Open Source License

private IPreferenceNode addNode(String category, String id, String name, IConfigurationElement config) {
    IPreferenceNode parent = find(category);
    PreferenceNode node = new SubpagePreferenceNode(id, name, config);
    if (parent != null)
        parent.add(node);
    return node;/*from w  w w .  j a v a  2  s. co  m*/
}

From source file:org.eclipse.ui.internal.dialogs.WorkbenchPreferenceManager.java

License:Open Source License

public void addExtension(IExtensionTracker tracker, IExtension extension) {
    IConfigurationElement[] elements = extension.getConfigurationElements();
    for (int i = 0; i < elements.length; i++) {
        WorkbenchPreferenceNode node = PreferencePageRegistryReader.createNode(elements[i]);
        if (node == null) {
            continue;
        }/*from   ww w  .j a va2 s .  c om*/
        registerNode(node);
        String category = node.getCategory();
        if (category == null) {
            addToRoot(node);
        } else {
            IPreferenceNode parent = null;
            for (Iterator j = getElements(PreferenceManager.POST_ORDER).iterator(); j.hasNext();) {
                IPreferenceNode element = (IPreferenceNode) j.next();
                if (category.equals(element.getId())) {
                    parent = element;
                    break;
                }
            }
            if (parent == null) {
                // Could not find the parent - log
                String message = "Invalid preference category path: " + category + " (bundle: " //$NON-NLS-1$//$NON-NLS-2$
                        + node.getPluginId() + ", page: " + node.getId() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ 
                WorkbenchPlugin.log(StatusUtil.newStatus(IStatus.WARNING, message, null));
                addToRoot(node);
            } else {
                parent.add(node);
            }
        }
    }
}

From source file:org.eclipse.ui.tests.preferences.PreferencesDialogTest.java

License:Open Source License

/**
 * Test preference dialog with a custom manager, custom nodes.
 *///from   www .  j a  va  2 s .com
public void testCustomManager() {
    PreferenceManager manager = new PreferenceManager();

    IPreferencePage page1 = new SamplePreferencePage("Top", "First Sample");
    IPreferenceNode node1 = new PreferenceNode("Top", page1);
    manager.addToRoot(node1);

    IPreferencePage page2 = new SamplePreferencePage("Sub", "Second Sample");
    IPreferenceNode node2 = new PreferenceNode("Sub", page2);
    node1.add(node2);

    PreferenceDialog dialog = null;
    try {
        dialog = new PreferenceDialog(shell, manager);
        dialog.setBlockOnOpen(false);

        // Check that we can create a dialog with custom preference manager.
        // Should be no exceptions.
        dialog.open();
    } finally {
        if (dialog != null)
            dialog.close();
    }
}