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

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

Introduction

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

Prototype

public TreeViewer(Tree tree) 

Source Link

Document

Creates a tree viewer on the given tree control.

Usage

From source file:com.android.ddmuilib.explorer.DeviceExplorer.java

License:Apache License

/**
 * Creates a control capable of displaying some information.  This is
 * called once, when the application is initializing, from the UI thread.
 *///from w  w w  .ja v  a2 s  .  co m
@Override
protected Control createControl(Composite parent) {
    mParent = parent;
    parent.setLayout(new FillLayout());

    ImageLoader loader = ImageLoader.getDdmUiLibLoader();
    if (mFileImage == null) {
        mFileImage = loader.loadImage("file.png", mParent.getDisplay());
    }
    if (mFolderImage == null) {
        mFolderImage = loader.loadImage("folder.png", mParent.getDisplay());
    }
    if (mPackageImage == null) {
        mPackageImage = loader.loadImage("android.png", mParent.getDisplay());
    }
    if (mOtherImage == null) {
        // TODO: find a default image for other.
    }

    mTree = new Tree(parent, SWT.MULTI | SWT.FULL_SELECTION | SWT.VIRTUAL);
    mTree.setHeaderVisible(true);

    IPreferenceStore store = DdmUiPreferences.getStore();

    // create columns
    TableHelper.createTreeColumn(mTree, "Name", SWT.LEFT, "0000drwxrwxrwx", COLUMN_NAME, store); //$NON-NLS-2$
    TableHelper.createTreeColumn(mTree, "Size", SWT.RIGHT, "000000", COLUMN_SIZE, store); //$NON-NLS-2$
    TableHelper.createTreeColumn(mTree, "Date", SWT.LEFT, "2007-08-14", COLUMN_DATE, store); //$NON-NLS-2$
    TableHelper.createTreeColumn(mTree, "Time", SWT.LEFT, "20:54", COLUMN_TIME, store); //$NON-NLS-2$
    TableHelper.createTreeColumn(mTree, "Permissions", SWT.LEFT, "drwxrwxrwx", COLUMN_PERMISSIONS, store); //$NON-NLS-2$
    TableHelper.createTreeColumn(mTree, "Info", SWT.LEFT, "drwxrwxrwx", COLUMN_INFO, store); //$NON-NLS-2$

    // create the jface wrapper
    mTreeViewer = new TreeViewer(mTree);

    // setup data provider
    mContentProvider = new DeviceContentProvider();
    mTreeViewer.setContentProvider(mContentProvider);
    mTreeViewer.setLabelProvider(new FileLabelProvider(mFileImage, mFolderImage, mPackageImage, mOtherImage));

    // setup a listener for selection
    mTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            ISelection sel = event.getSelection();
            if (sel.isEmpty()) {
                mPullAction.setEnabled(false);
                mPushAction.setEnabled(false);
                mDeleteAction.setEnabled(false);
                mCreateNewFolderAction.setEnabled(false);
                return;
            }
            if (sel instanceof IStructuredSelection) {
                IStructuredSelection selection = (IStructuredSelection) sel;
                Object element = selection.getFirstElement();
                if (element == null)
                    return;
                if (element instanceof FileEntry) {
                    mPullAction.setEnabled(true);
                    mPushAction.setEnabled(selection.size() == 1);
                    if (selection.size() == 1) {
                        FileEntry entry = (FileEntry) element;
                        setDeleteEnabledState(entry);
                        mCreateNewFolderAction.setEnabled(entry.isDirectory());
                    } else {
                        mDeleteAction.setEnabled(false);
                    }
                }
            }
        }
    });

    // add support for double click
    mTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
        @Override
        public void doubleClick(DoubleClickEvent event) {
            ISelection sel = event.getSelection();

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

                if (selection.size() == 1) {
                    FileEntry entry = (FileEntry) selection.getFirstElement();
                    String name = entry.getName();

                    FileEntry parentEntry = entry.getParent();

                    // can't really do anything with no parent
                    if (parentEntry == null) {
                        return;
                    }

                    // check this is a file like we want.
                    Matcher m = mKeyFilePattern.matcher(name);
                    if (m.matches()) {
                        // get the name w/o the extension
                        String baseName = m.group(1);

                        // add the data extension
                        String dataName = baseName + TRACE_DATA_EXT;

                        FileEntry dataEntry = parentEntry.findChild(dataName);

                        handleTraceDoubleClick(baseName, entry, dataEntry);

                    } else {
                        m = mDataFilePattern.matcher(name);
                        if (m.matches()) {
                            // get the name w/o the extension
                            String baseName = m.group(1);

                            // add the key extension
                            String keyName = baseName + TRACE_KEY_EXT;

                            FileEntry keyEntry = parentEntry.findChild(keyName);

                            handleTraceDoubleClick(baseName, keyEntry, entry);
                        }
                    }
                }
            }
        }
    });

    // setup drop listener
    mTreeViewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, new Transfer[] { FileTransfer.getInstance() },
            new ViewerDropAdapter(mTreeViewer) {
                @Override
                public boolean performDrop(Object data) {
                    // get the item on which we dropped the item(s)
                    FileEntry target = (FileEntry) getCurrentTarget();

                    // in case we drop at the same level as root
                    if (target == null) {
                        return false;
                    }

                    // if the target is not a directory, we get the parent directory
                    if (target.isDirectory() == false) {
                        target = target.getParent();
                    }

                    if (target == null) {
                        return false;
                    }

                    // get the list of files to drop
                    String[] files = (String[]) data;

                    // do the drop
                    pushFiles(files, target);

                    // we need to finish with a refresh
                    refresh(target);

                    return true;
                }

                @Override
                public boolean validateDrop(Object target, int operation, TransferData transferType) {
                    if (target == null) {
                        return false;
                    }

                    // convert to the real item
                    FileEntry targetEntry = (FileEntry) target;

                    // if the target is not a directory, we get the parent directory
                    if (targetEntry.isDirectory() == false) {
                        target = targetEntry.getParent();
                    }

                    if (target == null) {
                        return false;
                    }

                    return true;
                }
            });

    // create and start the refresh thread
    new Thread("Device Ls refresher") {
        @Override
        public void run() {
            while (true) {
                try {
                    sleep(FileListingService.REFRESH_RATE);
                } catch (InterruptedException e) {
                    return;
                }

                if (mTree != null && mTree.isDisposed() == false) {
                    Display display = mTree.getDisplay();
                    if (display.isDisposed() == false) {
                        display.asyncExec(new Runnable() {
                            @Override
                            public void run() {
                                if (mTree.isDisposed() == false) {
                                    mTreeViewer.refresh(true);
                                }
                            }
                        });
                    } else {
                        return;
                    }
                } else {
                    return;
                }
            }

        }
    }.start();

    return mTree;
}

From source file:com.android.ddmuilib.heap.NativeHeapPanel.java

License:Apache License

private void initializeDetailsTree(Tree tree) {
    tree.setHeaderVisible(true);/*from   ww w  . j  a  va 2 s. com*/
    tree.setLinesVisible(true);

    List<String> properties = Arrays.asList("Library", "Total", "Percentage", "Count", "Size", "Method");

    List<String> sampleValues = Arrays.asList("/path/in/device/to/system/library.so", "123456789", " 100%",
            "123456789", "123456789", "PossiblyLongDemangledMethodName");

    // right align numeric values
    List<Integer> swtFlags = Arrays.asList(SWT.LEFT, SWT.RIGHT, SWT.RIGHT, SWT.RIGHT, SWT.RIGHT, SWT.LEFT);

    for (int i = 0; i < properties.size(); i++) {
        String p = properties.get(i);
        String v = sampleValues.get(i);
        int flags = swtFlags.get(i);
        TableHelper.createTreeColumn(tree, p, flags, v, getPref("details", p), mPrefStore);
    }

    mDetailsTreeViewer = new TreeViewer(tree);

    mDetailsTreeViewer.setUseHashlookup(true);

    boolean displayZygotes = mPrefStore.getBoolean(PREFS_SHOW_ZYGOTE_ALLOCATIONS);
    mContentProviderByAllocations = new NativeHeapProviderByAllocations(mDetailsTreeViewer, displayZygotes);
    mContentProviderByLibrary = new NativeHeapProviderByLibrary(mDetailsTreeViewer, displayZygotes);
    if (mPrefStore.getBoolean(PREFS_GROUP_BY_LIBRARY)) {
        mDetailsTreeViewer.setContentProvider(mContentProviderByLibrary);
    } else {
        mDetailsTreeViewer.setContentProvider(mContentProviderByAllocations);
    }

    mDetailsTreeLabelProvider = new NativeHeapLabelProvider();
    mDetailsTreeViewer.setLabelProvider(mDetailsTreeLabelProvider);

    mDetailsTreeViewer.setInput(null);

    tree.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            displayStackTraceForSelection();
        }
    });
}

From source file:com.android.ddmuilib.heap.NativeHeapPanel.java

License:Apache License

private void initializeStackTraceTree(Tree tree) {
    tree.setHeaderVisible(true);/*ww  w.  j av  a  2s  .  c  o m*/
    tree.setLinesVisible(true);

    List<String> properties = Arrays.asList("Address", "Library", "Method", "File", "Line");

    List<String> sampleValues = Arrays.asList("0x1234_5678", "/path/in/device/to/system/library.so",
            "PossiblyLongDemangledMethodName",
            "/android/out/prefix/in/home/directory/to/path/in/device/to/system/library.so", "2000");

    for (int i = 0; i < properties.size(); i++) {
        String p = properties.get(i);
        String v = sampleValues.get(i);
        TableHelper.createTreeColumn(tree, p, SWT.LEFT, v, getPref("stack", p), mPrefStore);
    }

    mStackTraceTreeViewer = new TreeViewer(tree);

    mStackTraceTreeViewer.setContentProvider(new NativeStackContentProvider());
    mStackTraceTreeViewer.setLabelProvider(new NativeStackLabelProvider());

    mStackTraceTreeViewer.setInput(null);
}

From source file:com.android.glesv2debugger.SampleView.java

License:Apache License

/**
 * This is a callback that will allow us to create the viewer and initialize
 * it.//w  w  w.  j ava 2  s  .c om
 */
@Override
public void createPartControl(Composite parent) {
    createLeftPane(parent);

    // Create the help context id for the viewer's control
    PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "GLESv2DebuggerClient.viewer");

    tabFolder = new TabFolder(parent, SWT.BORDER);

    text = new Text(tabFolder, SWT.NO_BACKGROUND | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);

    tabItemText = new TabItem(tabFolder, SWT.NONE);
    tabItemText.setText("Text");
    tabItemText.setControl(text);

    canvas = new Canvas(tabFolder, SWT.NO_BACKGROUND | SWT.NO_REDRAW_RESIZE | SWT.V_SCROLL | SWT.H_SCROLL);
    tabItemImage = new TabItem(tabFolder, SWT.NONE);
    tabItemImage.setText("Image");
    tabItemImage.setControl(canvas);

    breakpointOption = new BreakpointOption(this, tabFolder);
    tabItemBreakpointOption = new TabItem(tabFolder, SWT.NONE);
    tabItemBreakpointOption.setText("Breakpoint Option");
    tabItemBreakpointOption.setControl(breakpointOption);

    shaderEditor = new ShaderEditor(this, tabFolder);
    tabItemShaderEditor = new TabItem(tabFolder, SWT.NONE);
    tabItemShaderEditor.setText("Shader Editor");
    tabItemShaderEditor.setControl(shaderEditor);

    contextViewer = new TreeViewer(tabFolder);
    ContextViewProvider contextViewProvider = new ContextViewProvider(this);
    contextViewer.addSelectionChangedListener(contextViewProvider);
    contextViewer.setContentProvider(contextViewProvider);
    contextViewer.setLabelProvider(contextViewProvider);
    tabContextViewer = new TabItem(tabFolder, SWT.NONE);
    tabContextViewer.setText("Context Viewer");
    tabContextViewer.setControl(contextViewer.getTree());

    final ScrollBar hBar = canvas.getHorizontalBar();
    hBar.addListener(SWT.Selection, new Listener() {
        @Override
        public void handleEvent(Event e) {
            if (null == canvas.getBackgroundImage())
                return;
            Image image = canvas.getBackgroundImage();
            int hSelection = hBar.getSelection();
            int destX = -hSelection - origin.x;
            Rectangle rect = image.getBounds();
            canvas.scroll(destX, 0, 0, 0, rect.width, rect.height, false);
            origin.x = -hSelection;
        }
    });
    final ScrollBar vBar = canvas.getVerticalBar();
    vBar.addListener(SWT.Selection, new Listener() {
        @Override
        public void handleEvent(Event e) {
            if (null == canvas.getBackgroundImage())
                return;
            Image image = canvas.getBackgroundImage();
            int vSelection = vBar.getSelection();
            int destY = -vSelection - origin.y;
            Rectangle rect = image.getBounds();
            canvas.scroll(0, destY, 0, 0, rect.width, rect.height, false);
            origin.y = -vSelection;
        }
    });
    canvas.addListener(SWT.Resize, new Listener() {
        @Override
        public void handleEvent(Event e) {
            if (null == canvas.getBackgroundImage())
                return;
            Image image = canvas.getBackgroundImage();
            Rectangle rect = image.getBounds();
            Rectangle client = canvas.getClientArea();
            hBar.setMaximum(rect.width);
            vBar.setMaximum(rect.height);
            hBar.setThumb(Math.min(rect.width, client.width));
            vBar.setThumb(Math.min(rect.height, client.height));
            int hPage = rect.width - client.width;
            int vPage = rect.height - client.height;
            int hSelection = hBar.getSelection();
            int vSelection = vBar.getSelection();
            if (hSelection >= hPage) {
                if (hPage <= 0)
                    hSelection = 0;
                origin.x = -hSelection;
            }
            if (vSelection >= vPage) {
                if (vPage <= 0)
                    vSelection = 0;
                origin.y = -vSelection;
            }
            canvas.redraw();
        }
    });
    canvas.addListener(SWT.Paint, new Listener() {
        @Override
        public void handleEvent(Event e) {
            if (null == canvas.getBackgroundImage())
                return;
            Image image = canvas.getBackgroundImage();
            GC gc = e.gc;
            gc.drawImage(image, origin.x, origin.y);
            Rectangle rect = image.getBounds();
            Rectangle client = canvas.getClientArea();
            int marginWidth = client.width - rect.width;
            if (marginWidth > 0) {
                gc.fillRectangle(rect.width, 0, marginWidth, client.height);
            }
            int marginHeight = client.height - rect.height;
            if (marginHeight > 0) {
                gc.fillRectangle(0, rect.height, client.width, marginHeight);
            }
        }
    });

    hookContextMenu();
    hookSelectionChanged();
    contributeToActionBars();

    messageQueue = new MessageQueue(this, new ProcessMessage[] { breakpointOption, shaderEditor });
}

From source file:com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigManagerDialog.java

License:Open Source License

@Override
public void createDialogContent(final Composite parent) {
    GridData gd;//from w ww.  j a  va 2s .  co m
    GridLayout gl;

    Tree tree = new Tree(parent, SWT.SINGLE | SWT.FULL_SELECTION);
    tree.setLayoutData(gd = new GridData(GridData.FILL_BOTH));
    gd.widthHint = 700;

    tree.setHeaderVisible(true);
    tree.setLinesVisible(true);
    TableHelper.createTreeColumn(tree, "Name", SWT.LEFT, 150, COL_NAME,
            AdtPlugin.getDefault().getPreferenceStore());
    TableHelper.createTreeColumn(tree, "Configuration", SWT.LEFT, 500, COL_CONFIG,
            AdtPlugin.getDefault().getPreferenceStore());

    mTreeViewer = new TreeViewer(tree);
    mTreeViewer.setContentProvider(new DeviceContentProvider());
    mTreeViewer.setLabelProvider(new DeviceLabelProvider());
    mTreeViewer.setAutoExpandLevel(TreeViewer.ALL_LEVELS);
    mTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            setEnabled(getSelection());
        }
    });

    Composite buttons = new Composite(parent, SWT.NONE);
    buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
    buttons.setLayout(gl = new GridLayout());
    gl.marginHeight = gl.marginWidth = 0;

    mNewButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
    mNewButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    mNewButton.setText("New...");
    mNewButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            DeviceSelection selection = getSelection();

            ConfigEditDialog dlg = new ConfigEditDialog(parent.getShell(), null);
            if (selection.device != null) {
                dlg.setDeviceName(selection.device.getName());
                dlg.setXDpi(selection.device.getXDpi());
                dlg.setYDpi(selection.device.getYDpi());
            }
            if (selection.config != null) {
                dlg.setConfigName(selection.config.getName());
                dlg.setConfig(selection.config.getConfig());
            }

            if (dlg.open() == Window.OK) {
                String deviceName = dlg.getDeviceName();
                String configName = dlg.getConfigName();
                FolderConfiguration config = new FolderConfiguration();
                dlg.getConfig(config);

                // first if there was no original device, we create one.
                // Because the new button is disabled when something else than "custom" is
                // selected, we always add to the user devices without checking.
                LayoutDevice d;
                if (selection.device == null) {
                    // FIXME: this doesn't check if the device name is taken.
                    d = mManager.addUserDevice(deviceName, dlg.getXDpi(), dlg.getYDpi());
                } else {
                    // search for it.
                    d = mManager.getUserLayoutDevice(deviceName);
                }

                if (d != null) {
                    // then if there was no config, we add it, otherwise we edit it
                    // (same method that adds/replace a config).
                    // FIXME this doesn't check if the name was already taken.
                    mManager.addUserConfiguration(d, configName, config);

                    mTreeViewer.refresh();
                    select(d, configName);
                }
            }
        }
    });

    mEditButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
    mEditButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    mEditButton.setText("Edit...");
    mEditButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            DeviceSelection selection = getSelection();
            ConfigEditDialog dlg = new ConfigEditDialog(parent.getShell(), null);
            dlg.setDeviceName(selection.device.getName());
            dlg.setXDpi(selection.device.getXDpi());
            dlg.setYDpi(selection.device.getYDpi());
            dlg.setConfigName(selection.config.getName());
            dlg.setConfig(selection.config.getConfig());

            if (dlg.open() == Window.OK) {
                String deviceName = dlg.getDeviceName();
                String configName = dlg.getConfigName();
                FolderConfiguration config = new FolderConfiguration();
                dlg.getConfig(config);

                // replace the device if needed.
                // FIXME: this doesn't check if the replacement name doesn't exist already.
                LayoutDevice d = mManager.replaceUserDevice(selection.device, deviceName, dlg.getXDpi(),
                        dlg.getYDpi());

                // and add/replace the config
                mManager.replaceUserConfiguration(d, selection.config.getName(), configName, config);

                mTreeViewer.refresh();
                select(d, configName);
            }
        }
    });

    mCopyButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
    mCopyButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    mCopyButton.setText("Copy");
    mCopyButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            DeviceSelection selection = getSelection();

            // is the source a default/add-on device, or are we copying a full device?
            // if so the target device is a new device.
            LayoutDevice targetDevice = selection.device;
            if (selection.type == DeviceType.DEFAULT || selection.type == DeviceType.ADDON
                    || selection.config == null) {
                // create a new device
                targetDevice = mManager.addUserDevice(selection.device.getName() + " Copy", // new name
                        selection.device.getXDpi(), selection.device.getYDpi());
            }

            String newConfigName = null; // name of the single new config. used for the select.

            // are we copying the full device?
            if (selection.config == null) {
                // get the config from the origin device
                List<DeviceConfig> configs = selection.device.getConfigs();

                // and copy them in the target device
                for (DeviceConfig config : configs) {
                    // we need to make a copy of the config object, or it could be modified
                    // in default/addon by editing the version in the new device.
                    FolderConfiguration copy = new FolderConfiguration();
                    copy.set(config.getConfig());

                    // the name can stay the same since we are copying a full device
                    // and the target device has its own new name.
                    mManager.addUserConfiguration(targetDevice, config.getName(), copy);
                }
            } else {
                // only copy the config. target device is not the same as the selection, don't
                // change the config name as we already changed the name of the device.
                newConfigName = (selection.device != targetDevice) ? selection.config.getName()
                        : selection.config.getName() + " Copy";

                // copy of the config
                FolderConfiguration copy = new FolderConfiguration();
                copy.set(selection.config.getConfig());

                // and create the config
                mManager.addUserConfiguration(targetDevice, newConfigName, copy);
            }

            mTreeViewer.refresh();

            select(targetDevice, newConfigName);
        }
    });

    mDeleteButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
    mDeleteButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    mDeleteButton.setText("Delete");
    mDeleteButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            DeviceSelection selection = getSelection();

            if (selection.config != null) {
                mManager.removeUserConfiguration(selection.device, selection.config.getName());
            } else if (selection.device != null) {
                mManager.removeUserDevice(selection.device);
            }

            mTreeViewer.refresh();

            // either select the device (if we removed a entry, or the top custom node if
            // we removed a device)
            select(selection.config != null ? selection.device : null, null);
        }
    });

    Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
    separator.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
    gd.horizontalSpan = 2;

    mTreeViewer.setInput(mManager);
    setEnabled(null); // no selection at the start
}

From source file:com.android.ide.eclipse.adt.internal.editors.ui.tree.UiTreeBlock.java

License:Open Source License

/**
 * Creates the tree and its viewer//from  w w  w .ja  v  a 2  s.  com
 * @return The tree control
 */
private Tree createTreeViewer(FormToolkit toolkit, Composite grid, final IManagedForm managedForm) {
    // Note: we *could* use a FilteredTree instead of the Tree+TreeViewer here.
    // However the class must be adapted to create an adapted toolkit tree.
    final Tree tree = toolkit.createTree(grid, SWT.MULTI);
    GridData gd = new GridData(GridData.FILL_BOTH);
    gd.widthHint = AndroidXmlEditor.TEXT_WIDTH_HINT;
    gd.heightHint = TREE_HEIGHT_HINT;
    tree.setLayoutData(gd);

    mTreeViewer = new TreeViewer(tree);
    mTreeViewer.setContentProvider(new UiModelTreeContentProvider(mUiRootNode, mDescriptorFilters));
    mTreeViewer.setLabelProvider(new UiModelTreeLabelProvider());
    mTreeViewer.setInput("unused"); //$NON-NLS-1$

    // Create a listener that reacts to selections on the tree viewer.
    // When a selection is made, ask the managed form to propagate an event to
    // all parts in the managed form.
    // This is picked up by UiElementDetail.selectionChanged().
    mTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            managedForm.fireSelectionChanged(mMasterPart, event.getSelection());
            adjustTreeButtons(event.getSelection());
        }
    });

    // Create three listeners:
    // - One to refresh the tree viewer when the parent's node has been updated
    // - One to refresh the tree viewer when the framework resources have changed
    // - One to enable/disable the UI based on the application node's presence.
    mUiRefreshListener = new IUiUpdateListener() {
        @Override
        public void uiElementNodeUpdated(UiElementNode ui_node, UiUpdateState state) {
            mTreeViewer.refresh();
        }
    };

    mUiEnableListener = new IUiUpdateListener() {
        @Override
        public void uiElementNodeUpdated(UiElementNode ui_node, UiUpdateState state) {
            // The UiElementNode for the application XML node always exists, even
            // if there is no corresponding XML node in the XML file.
            //
            // Normally, we enable the UI here if the XML node is not null.
            //
            // However if mAutoCreateRoot is true, the root node will be created on-demand
            // so the tree/block is always enabled.
            boolean exists = mAutoCreateRoot || (ui_node.getXmlNode() != null);
            if (mMasterPart != null) {
                Section section = mMasterPart.getSection();
                if (section.getEnabled() != exists) {
                    section.setEnabled(exists);
                    for (Control c : section.getChildren()) {
                        c.setEnabled(exists);
                    }
                }
            }
        }
    };

    /** Listener to update the root node if the target of the file is changed because of a
     * SDK location change or a project target change */
    final ITargetChangeListener targetListener = new TargetChangeListener() {
        @Override
        public IProject getProject() {
            if (mEditor != null) {
                return mEditor.getProject();
            }

            return null;
        }

        @Override
        public void reload() {
            // If a details part has been created, we need to "refresh" it too.
            if (mDetailsPart != null) {
                // The details part does not directly expose access to its internal
                // page book. Instead it is possible to resize the page book to 0 and then
                // back to its original value, which has the side effect of removing all
                // existing cached pages.
                int limit = mDetailsPart.getPageLimit();
                mDetailsPart.setPageLimit(0);
                mDetailsPart.setPageLimit(limit);
            }
            // Refresh the tree, preserving the selection if possible.
            mTreeViewer.refresh();
        }
    };

    // Setup the listeners
    changeRootAndDescriptors(mUiRootNode, mDescriptorFilters, false /* refresh */);

    // Listen on resource framework changes to refresh the tree
    AdtPlugin.getDefault().addTargetListener(targetListener);

    // Remove listeners when the tree widget gets disposed.
    tree.addDisposeListener(new DisposeListener() {
        @Override
        public void widgetDisposed(DisposeEvent e) {
            if (mUiRootNode != null) {
                UiElementNode node = mUiRootNode.getUiParent() != null ? mUiRootNode.getUiParent()
                        : mUiRootNode;

                if (node != null) {
                    node.removeUpdateListener(mUiRefreshListener);
                }
                mUiRootNode.removeUpdateListener(mUiEnableListener);
            }

            AdtPlugin.getDefault().removeTargetListener(targetListener);
            if (mClipboard != null) {
                mClipboard.dispose();
                mClipboard = null;
            }
        }
    });

    // Get a new clipboard reference. It is disposed when the tree is disposed.
    mClipboard = new Clipboard(tree.getDisplay());

    return tree;
}

From source file:com.android.ide.eclipse.adt.internal.ui.ResourceExplorerView.java

License:Open Source License

@Override
public void createPartControl(Composite parent) {
    mTree = new Tree(parent, SWT.SINGLE | SWT.VIRTUAL);
    mTree.setLayoutData(new GridData(GridData.FILL_BOTH));
    mTree.setHeaderVisible(true);/*from ww  w. j  ava  2 s  . co  m*/
    mTree.setLinesVisible(true);

    final IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();

    // create 2 columns. The main one with the resources, and an "info" column.
    createTreeColumn(mTree, "Resources", SWT.LEFT, "abcdefghijklmnopqrstuvwxz", -1, PREFS_COLUMN_RES, store); //$NON-NLS-2$
    createTreeColumn(mTree, "Info", SWT.LEFT, "0123456789", -1, PREFS_COLUMN_2, store); //$NON-NLS-2$

    // create the jface wrapper
    mTreeViewer = new TreeViewer(mTree);

    mTreeViewer.setContentProvider(new ResourceContentProvider(true /* fullLevels */));
    mTreeViewer.setLabelProvider(new ResourceLabelProvider());

    // listen to selection change in the workbench.
    IWorkbenchPage page = getSite().getPage();

    page.addSelectionListener(this);

    // init with current selection
    selectionChanged(getSite().getPart(), page.getSelection());

    // add support for double click.
    mTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
        @Override
        public void doubleClick(DoubleClickEvent event) {
            ISelection sel = event.getSelection();

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

                if (selection.size() == 1) {
                    Object element = selection.getFirstElement();

                    // if it's a resourceFile, we directly open it.
                    if (element instanceof ResourceFile) {
                        try {
                            IAbstractFile iAbstractFile = ((ResourceFile) element).getFile();
                            if (iAbstractFile instanceof IFileWrapper) {
                                IDE.openEditor(getSite().getWorkbenchWindow().getActivePage(),
                                        ((IFileWrapper) iAbstractFile).getIFile());
                            }
                        } catch (PartInitException e) {
                        }
                    } else if (element instanceof ResourceItem) {
                        // if it's a ResourceItem, we open the first file, but only if
                        // there's no alternate files.
                        ResourceItem item = (ResourceItem) element;

                        if (item.isEditableDirectly()) {
                            ResourceFile[] files = item.getSourceFileArray();
                            if (files[0] != null) {
                                try {
                                    IAbstractFile iAbstractFile = files[0].getFile();
                                    if (iAbstractFile instanceof IFileWrapper) {
                                        IDE.openEditor(getSite().getWorkbenchWindow().getActivePage(),
                                                ((IFileWrapper) iAbstractFile).getIFile());
                                    }
                                } catch (PartInitException e) {
                                }
                            }
                        }
                    }
                }
            }
        }
    });

    // set up the resource manager to send us resource change notification
    AdtPlugin.getDefault().getResourceMonitor().addResourceEventListener(this);
}

From source file:com.android.ide.eclipse.auidt.internal.editors.layout.configuration.ConfigManagerDialog.java

License:Open Source License

@Override
public void createDialogContent(final Composite parent) {
    GridData gd;/*from  w w w  . j  av  a 2s  .  c  o  m*/
    GridLayout gl;

    Tree tree = new Tree(parent, SWT.SINGLE | SWT.FULL_SELECTION);
    tree.setLayoutData(gd = new GridData(GridData.FILL_BOTH));
    gd.widthHint = 700;

    tree.setHeaderVisible(true);
    tree.setLinesVisible(true);
    TableHelper.createTreeColumn(tree, "Name", SWT.LEFT, 150, COL_NAME,
            AdtPlugin.getDefault().getPreferenceStore());
    TableHelper.createTreeColumn(tree, "Configuration", SWT.LEFT, 500, COL_CONFIG,
            AdtPlugin.getDefault().getPreferenceStore());

    mTreeViewer = new TreeViewer(tree);
    mTreeViewer.setContentProvider(new DeviceContentProvider());
    mTreeViewer.setLabelProvider(new DeviceLabelProvider());
    mTreeViewer.setAutoExpandLevel(TreeViewer.ALL_LEVELS);
    mTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            setEnabled(getSelection());
        }
    });

    Composite buttons = new Composite(parent, SWT.NONE);
    buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
    buttons.setLayout(gl = new GridLayout());
    gl.marginHeight = gl.marginWidth = 0;

    mNewButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
    mNewButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    mNewButton.setText("New...");
    mNewButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            DeviceSelection selection = getSelection();

            ConfigEditDialog dlg = new ConfigEditDialog(parent.getShell(), null);
            if (selection.device != null) {
                dlg.setDeviceName(selection.device.getName());
                dlg.setXDpi(selection.device.getXDpi());
                dlg.setYDpi(selection.device.getYDpi());
            }
            if (selection.config != null) {
                dlg.setConfigName(selection.config.getName());
                dlg.setConfig(selection.config.getConfig());
            }

            if (dlg.open() == Window.OK) {
                String deviceName = dlg.getDeviceName();
                String configName = dlg.getConfigName();
                FolderConfiguration config = new FolderConfiguration();
                dlg.getConfig(config);

                // first if there was no original device, we create one.
                // Because the new button is disabled when something else than "custom" is
                // selected, we always add to the user devices without checking.
                LayoutDevice d;
                if (selection.device == null) {
                    // FIXME: this doesn't check if the device name is taken.
                    d = mManager.addUserDevice(deviceName, dlg.getXDpi(), dlg.getYDpi());
                } else {
                    // search for it.
                    d = mManager.getUserLayoutDevice(deviceName);
                }

                if (d != null) {
                    // then if there was no config, we add it, otherwise we edit it
                    // (same method that adds/replace a config).
                    // FIXME this doesn't check if the name was already taken.
                    mManager.addUserConfiguration(d, configName, config);

                    mTreeViewer.refresh();
                    select(d, configName);
                }
            }
        }
    });

    mEditButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
    mEditButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    mEditButton.setText("Edit...");
    mEditButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            DeviceSelection selection = getSelection();
            ConfigEditDialog dlg = new ConfigEditDialog(parent.getShell(), null);
            dlg.setDeviceName(selection.device.getName());
            dlg.setXDpi(selection.device.getXDpi());
            dlg.setYDpi(selection.device.getYDpi());
            dlg.setConfigName(selection.config.getName());
            dlg.setConfig(selection.config.getConfig());

            if (dlg.open() == Window.OK) {
                String deviceName = dlg.getDeviceName();
                String configName = dlg.getConfigName();
                FolderConfiguration config = new FolderConfiguration();
                dlg.getConfig(config);

                // replace the device if needed.
                // FIXME: this doesn't check if the replacement name doesn't exist already.
                LayoutDevice d = mManager.replaceUserDevice(selection.device, deviceName, dlg.getXDpi(),
                        dlg.getYDpi());

                // and add/replace the config
                mManager.replaceUserConfiguration(d, selection.config.getName(), configName, config);

                mTreeViewer.refresh();
                select(d, configName);
            }
        }
    });

    mCopyButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
    mCopyButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    mCopyButton.setText("Copy");
    mCopyButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            DeviceSelection selection = getSelection();

            // is the source a default/add-on device, or are we copying a full device?
            // if so the target device is a new device.
            LayoutDevice targetDevice = selection.device;
            if (selection.type == DeviceType.DEFAULT || selection.type == DeviceType.ADDON
                    || selection.config == null) {
                // create a new device
                targetDevice = mManager.addUserDevice(selection.device.getName() + " Copy", // new name
                        selection.device.getXDpi(), selection.device.getYDpi());
            }

            String newConfigName = null; // name of the single new config. used for the select.

            // are we copying the full device?
            if (selection.config == null) {
                // get the config from the origin device
                List<DeviceConfig> configs = selection.device.getConfigs();

                // and copy them in the target device
                for (DeviceConfig config : configs) {
                    // we need to make a copy of the config object, or it could be modified
                    // in default/addon by editing the version in the new device.
                    FolderConfiguration copy = new FolderConfiguration();
                    copy.set(config.getConfig());

                    // the name can stay the same since we are copying a full device
                    // and the target device has its own new name.
                    mManager.addUserConfiguration(targetDevice, config.getName(), copy);
                }
            } else {
                // only copy the config. target device is not the same as the selection, don't
                // change the config name as we already changed the name of the device.
                newConfigName = (selection.device != targetDevice) ? selection.config.getName()
                        : selection.config.getName() + " Copy";

                // copy of the config
                FolderConfiguration copy = new FolderConfiguration();
                copy.set(selection.config.getConfig());

                // and create the config
                mManager.addUserConfiguration(targetDevice, newConfigName, copy);
            }

            mTreeViewer.refresh();

            select(targetDevice, newConfigName);
        }
    });

    mDeleteButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
    mDeleteButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    mDeleteButton.setText("Delete");
    mDeleteButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            DeviceSelection selection = getSelection();

            if (selection.config != null) {
                mManager.removeUserConfiguration(selection.device, selection.config.getName());
            } else if (selection.device != null) {
                mManager.removeUserDevice(selection.device);
            }

            mTreeViewer.refresh();

            // either select the device (if we removed a entry, or the top custom node if
            // we removed a device)
            select(selection.config != null ? selection.device : null, null);
        }
    });

    Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
    separator.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
    gd.horizontalSpan = 2;

    mTreeViewer.setInput(mManager);
    setEnabled(null); // no selection at the start
}

From source file:com.android.ide.eclipse.editors.resources.explorer.ResourceExplorerView.java

License:Open Source License

@Override
public void createPartControl(Composite parent) {
    mTree = new Tree(parent, SWT.SINGLE | SWT.VIRTUAL);
    mTree.setLayoutData(new GridData(GridData.FILL_BOTH));
    mTree.setHeaderVisible(true);//from  ww w  .j a v  a 2  s  .c  o  m
    mTree.setLinesVisible(true);

    final IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();

    // create 2 columns. The main one with the resources, and an "info" column.
    createTreeColumn(mTree, "Resources", SWT.LEFT, "abcdefghijklmnopqrstuvwxz", -1, PREFS_COLUMN_RES, store); //$NON-NLS-2$
    createTreeColumn(mTree, "Info", SWT.LEFT, "0123456789", -1, PREFS_COLUMN_2, store); //$NON-NLS-2$

    // create the jface wrapper
    mTreeViewer = new TreeViewer(mTree);

    mTreeViewer.setContentProvider(new ResourceContentProvider(true /* fullLevels */));
    mTreeViewer.setLabelProvider(new ResourceLabelProvider());

    // listen to selection change in the workbench.
    IWorkbenchPage page = getSite().getPage();

    page.addSelectionListener(this);

    // init with current selection
    selectionChanged(getSite().getPart(), page.getSelection());

    // add support for double click.
    mTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
        public void doubleClick(DoubleClickEvent event) {
            ISelection sel = event.getSelection();

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

                if (selection.size() == 1) {
                    Object element = selection.getFirstElement();

                    // if it's a resourceFile, we directly open it.
                    if (element instanceof ResourceFile) {
                        try {
                            IDE.openEditor(getSite().getWorkbenchWindow().getActivePage(),
                                    ((ResourceFile) element).getFile().getIFile());
                        } catch (PartInitException e) {
                        }
                    } else if (element instanceof ProjectResourceItem) {
                        // if it's a ResourceItem, we open the first file, but only if
                        // there's no alternate files.
                        ProjectResourceItem item = (ProjectResourceItem) element;

                        if (item.isEditableDirectly()) {
                            ResourceFile[] files = item.getSourceFileArray();
                            if (files[0] != null) {
                                try {
                                    IDE.openEditor(getSite().getWorkbenchWindow().getActivePage(),
                                            files[0].getFile().getIFile());
                                } catch (PartInitException e) {
                                }
                            }
                        }
                    }
                }
            }
        }
    });

    // set up the resource manager to send us resource change notification
    AdtPlugin.getDefault().getResourceMonitor().addResourceEventListener(this);
}

From source file:com.android.ide.eclipse.editors.ui.tree.UiTreeBlock.java

License:Open Source License

/**
 * Creates the tree and its viewer/*from   w w w  .j  a  v a 2s  . com*/
 * @return The tree control
 */
private Tree createTreeViewer(FormToolkit toolkit, Composite grid, final IManagedForm managedForm) {
    // Note: we *could* use a FilteredTree instead of the Tree+TreeViewer here.
    // However the class must be adapted to create an adapted toolkit tree.
    final Tree tree = toolkit.createTree(grid, SWT.MULTI);
    GridData gd = new GridData(GridData.FILL_BOTH);
    gd.widthHint = AndroidEditor.TEXT_WIDTH_HINT;
    gd.heightHint = TREE_HEIGHT_HINT;
    tree.setLayoutData(gd);

    mTreeViewer = new TreeViewer(tree);
    mTreeViewer.setContentProvider(new UiModelTreeContentProvider(mUiRootNode, mDescriptorFilters));
    mTreeViewer.setLabelProvider(new UiModelTreeLabelProvider());
    mTreeViewer.setInput("unused"); //$NON-NLS-1$

    // Create a listener that reacts to selections on the tree viewer.
    // When a selection is made, ask the managed form to propagate an event to
    // all parts in the managed form.
    // This is picked up by UiElementDetail.selectionChanged().
    mTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            managedForm.fireSelectionChanged(mMasterPart, event.getSelection());
            adjustTreeButtons(event.getSelection());
        }
    });

    // Create three listeners:
    // - One to refresh the tree viewer when the parent's node has been updated
    // - One to refresh the tree viewer when the framework resources have changed
    // - One to enable/disable the UI based on the application node's presence.
    mUiRefreshListener = new IUiUpdateListener() {
        public void uiElementNodeUpdated(UiElementNode ui_node, UiUpdateState state) {
            mTreeViewer.refresh();
        }
    };

    mUiEnableListener = new IUiUpdateListener() {
        public void uiElementNodeUpdated(UiElementNode ui_node, UiUpdateState state) {
            // The UiElementNode for the application XML node always exists, even
            // if there is no corresponding XML node in the XML file.
            //
            // Normally, we enable the UI here if the XML node is not null.
            //
            // However if mAutoCreateRoot is true, the root node will be created on-demand
            // so the tree/block is always enabled.
            boolean exists = mAutoCreateRoot || (ui_node.getXmlNode() != null);
            if (mMasterPart != null) {
                Section section = mMasterPart.getSection();
                if (section.getEnabled() != exists) {
                    section.setEnabled(exists);
                    for (Control c : section.getChildren()) {
                        c.setEnabled(exists);
                    }
                }
            }
        }
    };

    /** Listener to update the root node if the target of the file is changed because of a
     * SDK location change or a project target change */
    final ITargetChangeListener targetListener = new ITargetChangeListener() {
        public void onProjectTargetChange(IProject changedProject) {
            if (changedProject == mEditor.getProject()) {
                onTargetsLoaded();
            }
        }

        public void onTargetsLoaded() {
            // If a details part has been created, we need to "refresh" it too.
            if (mDetailsPart != null) {
                // The details part does not directly expose access to its internal
                // page book. Instead it is possible to resize the page book to 0 and then
                // back to its original value, which has the side effect of removing all
                // existing cached pages.
                int limit = mDetailsPart.getPageLimit();
                mDetailsPart.setPageLimit(0);
                mDetailsPart.setPageLimit(limit);
            }
            // Refresh the tree, preserving the selection if possible.
            mTreeViewer.refresh();
        }
    };

    // Setup the listeners
    changeRootAndDescriptors(mUiRootNode, mDescriptorFilters, false /* refresh */);

    // Listen on resource framework changes to refresh the tree
    AdtPlugin.getDefault().addTargetListener(targetListener);

    // Remove listeners when the tree widget gets disposed.
    tree.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent e) {
            UiElementNode node = mUiRootNode.getUiParent() != null ? mUiRootNode.getUiParent() : mUiRootNode;

            node.removeUpdateListener(mUiRefreshListener);
            mUiRootNode.removeUpdateListener(mUiEnableListener);

            AdtPlugin.getDefault().removeTargetListener(targetListener);
            if (mClipboard != null) {
                mClipboard.dispose();
                mClipboard = null;
            }
        }
    });

    // Get a new clipboard reference. It is disposed when the tree is disposed.
    mClipboard = new Clipboard(tree.getDisplay());

    return tree;
}