Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to use ViewerFilter on a TreeViewer?

I am applying a ViewerFilter to a tree of a few branches, but mostly leaves. The filter really applies to the leaves, using properties within the leaf. All branches are left untouched so that their leaves can appear.

However I would like to filter out branches that contain no selected leaves, and I can see no mechanism within ViewerFilter that allows this.

Is this possible at all?

For example, given the notional tree below (where b is a branch, a L is a leaf)

b0
  b1
    L2
    L4
    L8
  b2
    L1
    L3
    L5

I would like to apply a ViewerFilter that only selects even leaves and branches that contain even leaves. The resulting tree would be ..

b0
  b1
    L2
    L4
    L8

.. where branch b2 does not display as it contains no selected children, but branches b0 and b1 do.

like image 645
Martin Cowie Avatar asked Jun 23 '09 22:06

Martin Cowie


3 Answers

class MyFilter extends ViewerFilter{

  private boolean isLeaf(Object element){
    // implement this
  }

  private boolean isEvenLeaf(Object leaf){
    // implement this
  }

  @Override
  public boolean select(Viewer viewer, Object parentElement, Object element){
    if (isLeaf(element))
      return isEventLeaf(element);
    else {
      StructuredViewer sviewer = (StructuredViewer) viewer;
      ITreeContentProvider provider = (ITreeContentProvider) sviewer.getContentProvider();
      for (Object child: provider.getChildren(element)){
        if (select(viewer, element, child))
          return true;
      }
      return false;
    }
  }
}
like image 51
Santhosh Kumar Tekuri Avatar answered Oct 22 '22 21:10

Santhosh Kumar Tekuri


Yes, if you don't filter out the branch nodes, they'll be shown even if there are no leaves in it. If you want the filter to be permanently on, something you can consider is using the ITreeContentProvider as a filter.

Since the content provider has both getChildren() and hasChildren() methods, you have a little more control.

like image 26
thehiatus Avatar answered Oct 22 '22 23:10

thehiatus


Also have a look at org.eclipse.ui.dialogs.FilteredTree which the right thing in regard to child leaves.

like image 30
Tonny Madsen Avatar answered Oct 22 '22 21:10

Tonny Madsen