07 - Eclipse Plugin Views Tutorial

In eclipse the entire workbench contains one or more workbench windows. Each workbench window may further contain one or more workbench pages and each page may contain one or more editor or views. An editor is typically used to edit/modify a workspace resource whereas Views are arranged around editors and provide assistance to editors in some way (though this is not always true). Views are used to display hierarchy of information, open up an editor or display properties for an active editor. Classic example of view is Package explorer and outline view. Package explorer is used to display workspace resources in a hierarchy and is used to open up associated editor whenever user performs double click action on the resource. Outline view is used to display information about the java resource for ex: package declaration, imports etc. (See figure below)

               outilne view to display Java resource

One of the key difference between editors and view is that editors are resource based i.e. they work on underlying resources in workspace. For ex: XML editor requires “.xml” file in workspace. Whereas, views may not be resource based. They can be used to show any kind of information. It is also important that we can make views which may display information irrespective of resources opened up in editor window (that’s why I said its not always true that view plays role of assistant window around editor area).

Resource Manager View

      Resoure Manager view

In first chapter of this tutorial we created a Resource Manager view as part of plug-in creation. We have been playing around with our resource manager view for quite some time for ex: we added this view to our own customized perspective, added actions to Resource Manager view. However, Resource Manager view itself does not do anything useful – every time it is opened it just displays static model as shown below:

Let’s Manage Workspace Property Files

In this chapter, we will create Property File Manager View so that it does something useful and more meaningful rather then just displaying static data.

Property File Manager View will search the entire workspace for all the projects. In each project it will search for "Property Files" folder, In each such folder it will look out for all the files with ".properties" extension and display it to the user. This way we will end up with a view as shown in the figure below. Please note that a property file gets displayed in the Property File Manager view only when it is created inside Property Files folder.

            Property File Manager View

Property File Manager View

In order to create a new view, open up manifest editor – click on extensions tab. Right click on “org.eclipse.ui.views” extension and click on new > view (See figure below)

     Eclipse Plugin Create a New View.

It will immediately open up Extension element details page. Edit the element details as shown below

        Eclipse Plugin set extension element details

 In order to create “com.myplugin.rmp.views.PropertyManagerView” class click on the class link to open up Java attribute editor as shown below:

         Eclipse Plugin Java Attibute Editor

Click finish to generate the Property Manager View class.

Complete Listing of the Property Manager View Class

What follows is the complete listing of Property Manager View class. However, before we move ahead to show this listing we will need to add two dependencies (if not already added) in the plug-in manifest editor. 

First dependency (org.eclipse.core.resources) is required since property manager needs to access workspace resources.

Second dependency (org.eclipse.ui.ide) is required since we will open up associated editor whenever user clicks on listed property files in property manager view.

       Eclipse Plugin add Second Dependency

In order to add the dependencies, open up manifest editor – click on dependencies tab and add above two dependencies as shown in fig below:

Once the dependencies have been added following code listing will compile successfully.
    

1.   package com.myplugin.rmp.views;
2.   import java.util.ArrayList;
3.   import org.eclipse.core.resources.IFile;
4.   import org.eclipse.core.resources.IFolder;
5.   import org.eclipse.core.resources.IProject;
6.   import org.eclipse.core.resources.IResource;
7.   import org.eclipse.core.resources.IWorkspace;
8.   import org.eclipse.core.resources.ResourcesPlugin;
9.   import org.eclipse.core.runtime.IAdaptable;
10.  import org.eclipse.jface.action.Action;
11.  import org.eclipse.jface.action.MenuManager;
12.  import org.eclipse.jface.dialogs.MessageDialog;
13.  import org.eclipse.jface.viewers.DoubleClickEvent;
14.  import org.eclipse.jface.viewers.IDoubleClickListener;
15.  import org.eclipse.jface.viewers.ISelection;
16.  import org.eclipse.jface.viewers.IStructuredContentProvider;
17.  import org.eclipse.jface.viewers.IStructuredSelection;
18.  import org.eclipse.jface.viewers.ITreeContentProvider;
19.  import org.eclipse.jface.viewers.LabelProvider;
20.  import org.eclipse.jface.viewers.TreeViewer;
21.  import org.eclipse.jface.viewers.Viewer;
22.  import org.eclipse.swt.SWT;
23.  import org.eclipse.swt.graphics.Image;
24.  import org.eclipse.swt.widgets.Composite;
25.  import org.eclipse.swt.widgets.Menu;
26.  import org.eclipse.ui.ISharedImages;
27.  import org.eclipse.ui.IWorkbenchPage;
28.  import org.eclipse.ui.PlatformUI;
29.  import org.eclipse.ui.ide.IDE;
30.  import org.eclipse.ui.part.ViewPart;

31. public class PropertyManagerView extends ViewPart {
32.           private TreeViewer viewer;
33.          private TreeParent invisibleRoot;

34.     class TreeObject implements IAdaptable {

35.          private String name;
36.          private TreeParent parent;
37.          private IResource resouce;

38.          public TreeObject(String name) {
39.                    this.name = name;
40.          }

41.          public String getName() {
42.                    return name;
43.          }

44.          public void setParent(TreeParent parent) {
45.                    this.parent = parent;
46.          }

47.          public TreeParent getParent() {
48.                    return parent;
49.          }

50.          public String toString() {
51.                    return getName();
52.          }

53.          public Object getAdapter(Class key) {
54.                    return null;
55.          }
56.          protected IResource getResouce() {
57.                    return resouce;
58.          }
59.          protected void setResouce(IResource resouce) {
60.                    this.resouce = resouce;
61.          }
62.    }
63.    class TreeParent extends TreeObject {
64.          private ArrayList children;
65.          public TreeParent(String name) {
66.                    super(name);
67.                    children = new ArrayList();
68.          }

69.          public void addChild(TreeObject child) {
70.                    children.add(child);
71.                    child.setParent(this);
72.          }

73.          public void removeChild(TreeObject child) {
74.                    children.remove(child);
75.                    child.setParent(null);
76.          }

77.          public TreeObject[] getChildren() {
78.                    return (TreeObject[]) children.toArray(new TreeObject[children.size()]);
79.          }

80.          public boolean hasChildren() {
81.                    return children.size() > 0;
82.          }


83.   }
84.   class ViewContentProvider implements ITreeContentProvider {

85.          public void inputChanged(Viewer v, Object oldInput, Object newInput) {
86.          }

87.          public void dispose() {
88.          }

89.          public Object[] getElements(Object parent) {
90.                    if (parent.equals(getViewSite())) {
91.                             if (invisibleRoot == null)
92.                                       initialize();

93.                             return getChildren(invisibleRoot);
94.                    }

95.                    return getChildren(parent);
96.          }

97.          public Object getParent(Object child) {
98.                    if (child instanceof TreeObject) {
99.                             return ((TreeObject) child).getParent();
100.                            }

101.                            return null;
102.                  }

103.                  public Object[] getChildren(Object parent) {

104.                            if (parent instanceof TreeParent) {
105.                                     return ((TreeParent) parent).getChildren();
106.                            }

107.                            return new Object[0];
108.                  }

109.                  public boolean hasChildren(Object parent) {
110.                            if (parent instanceof TreeParent)
111.                                     return ((TreeParent) parent).hasChildren();
112.                            return false;
113.                  }

114.         }

115.         class ViewLabelProvider extends LabelProvider {
116.                  public String getText(Object obj) {
117.                            return obj.toString();
118.                  }

119.                  public Image getImage(Object obj) {
120.                       String imageKey = ISharedImages.IMG_OBJ_ELEMENT;


121.                       if (obj instanceof TreeParent)
122.                         imageKey = ISharedImages.IMG_OBJ_FOLDER;
123.                         return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
124.                  }

125.         }

126.         public void initialize() {
127.                  TreeParent root = new TreeParent("WorkSpace Property Files");
128.                  try {
129.                      IWorkspace workspace = ResourcesPlugin.getWorkspace();

130.                      IProject[] projects = workspace.getRoot().getProjects();

131.                      for (int i = 0; i < projects.length; i++) {
132.                           IResource[] folderResources = projects[i].members();

133.                           for (int j = 0; j < folderResources.length; j++) {

134.                               if (folderResources[j] instanceof IFolder) {
135.                                  IFolder resource = (IFolder) folderResources[j];
136.                                  if (resource.getName().equalsIgnoreCase("Property Files")) {
137.                                     IResource[] fileResources = resource.members();
138.                                     for (int k = 0; k < fileResources.length; k++) {
139.                                        if (fileResources[k] instanceof IFile &&           
                                               fileResources[k].getName().endsWith(".properties")){
140.                                           TreeObject obj = new TreeObject(fileResources[k]
                                    .getName());
141.                                            obj.setResouce(fileResources[k]);
142.                                            root.addChild(obj);
143.                                         }
144.                                      }
145.                                     }
146.                               }
147.                           }
148.                       }
149.                  }catch (Exception e) {
                        // log exception
150.                  }
51.                  invisibleRoot = new TreeParent("");
152.                  invisibleRoot.addChild(root);
153.         }

154.         public PropertyManagerView() {
155.         }

156.         public void createPartControl(Composite parent) {
157.                  viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
158.                  viewer.setContentProvider(new ViewContentProvider());
159.                  viewer.setLabelProvider(new ViewLabelProvider());
160.                  viewer.setInput(getViewSite());
161.                  hookContextMenu();
162.                  hookDoubleCLickAction();
163.         }

164.         private void hookDoubleCLickAction() {
165.                  viewer.addDoubleClickListener(new IDoubleClickListener() {
166.                       public void doubleClick(DoubleClickEvent event) {
167.                            ISelection selection = event.getSelection();
168.                            Object obj = ((IStructuredSelection) selection).getFirstElement();
169.                            if (!(obj instanceof TreeObject)) {
170.                                  return;
171.                            }else {
172.                                 TreeObject tempObj = (TreeObject) obj;
173.                                 IFile ifile = ResourcesPlugin.getWorkspace().getRoot().
                          getFile(tempObj.getResouce().getFullPath());
174.                                 IWorkbenchPage dpage =
                                                    PropertyManagerView.this.getViewSite()
                                     .getWorkbenchWindow().getActivePage();
175.                                 if (dpage != null) {
176.                                     try {
177.                                           IDE.openEditor(dpage, ifile,true);
178.                                     }catch (Exception e) {
179.                                                      // log exception
180.                                  }
181.                             }
182.                        }
183.                    };
184.              });
185.         }

186.         private void hookContextMenu() {
187.                  MenuManager menuMgr = new MenuManager("#PopupMenu");
188.                  Menu menu = menuMgr.createContextMenu(viewer.getControl());
189.                  viewer.getControl().setMenu(menu);
190.                  Action refresh =new Action() {
191.                            public void run() {
192.                                     initialize();
193.                                     viewer.refresh();
194.                            }
195.                  };
196.                  refresh.setText("Refresh");
197.                  menuMgr.add(refresh);
198.         }

199.         public void setFocus() {
200.                  viewer.getControl().setFocus();
201.         }
202. }

Like us on Facebook