Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: com/port80/eclipse/jdt/method/MethodView.java


1   package com.port80.eclipse.jdt.method;
2   
3   import org.eclipse.core.internal.runtime.Assert;
4   import org.eclipse.core.resources.ResourcesPlugin;
5   import org.eclipse.core.runtime.IStatus;
6   import org.eclipse.core.runtime.Status;
7   import org.eclipse.jdt.core.IClassFile;
8   import org.eclipse.jdt.core.ICompilationUnit;
9   import org.eclipse.jdt.core.IJavaElement;
10  import org.eclipse.jdt.core.IMethod;
11  import org.eclipse.jdt.core.IType;
12  import org.eclipse.jdt.core.JavaModelException;
13  import org.eclipse.jdt.core.Signature;
14  import org.eclipse.jdt.internal.ui.JavaPlugin;
15  import org.eclipse.jdt.internal.ui.JavaPluginImages;
16  import org.eclipse.jface.action.Action;
17  import org.eclipse.jface.action.IMenuListener;
18  import org.eclipse.jface.action.IMenuManager;
19  import org.eclipse.jface.action.IToolBarManager;
20  import org.eclipse.jface.action.MenuManager;
21  import org.eclipse.jface.action.Separator;
22  import org.eclipse.jface.dialogs.MessageDialog;
23  import org.eclipse.jface.preference.IPreferenceStore;
24  import org.eclipse.jface.text.ITextSelection;
25  import org.eclipse.jface.util.IPropertyChangeListener;
26  import org.eclipse.jface.util.PropertyChangeEvent;
27  import org.eclipse.jface.viewers.DoubleClickEvent;
28  import org.eclipse.jface.viewers.IDoubleClickListener;
29  import org.eclipse.jface.viewers.ISelection;
30  import org.eclipse.jface.viewers.IStructuredSelection;
31  import org.eclipse.jface.viewers.StructuredSelection;
32  import org.eclipse.jface.viewers.TreeViewer;
33  import org.eclipse.swt.SWT;
34  import org.eclipse.swt.SWTError;
35  import org.eclipse.swt.dnd.Clipboard;
36  import org.eclipse.swt.dnd.DND;
37  import org.eclipse.swt.dnd.TextTransfer;
38  import org.eclipse.swt.dnd.Transfer;
39  import org.eclipse.swt.events.KeyEvent;
40  import org.eclipse.swt.events.KeyListener;
41  import org.eclipse.swt.widgets.Composite;
42  import org.eclipse.swt.widgets.Menu;
43  import org.eclipse.ui.IActionBars;
44  import org.eclipse.ui.IEditorPart;
45  import org.eclipse.ui.IMemento;
46  import org.eclipse.ui.IPartListener;
47  import org.eclipse.ui.ISelectionListener;
48  import org.eclipse.ui.ISharedImages;
49  import org.eclipse.ui.IViewSite;
50  import org.eclipse.ui.IWorkbenchPart;
51  import org.eclipse.ui.IWorkbenchPartSite;
52  import org.eclipse.ui.PartInitException;
53  import org.eclipse.ui.PlatformUI;
54  import org.eclipse.ui.internal.ILayoutContainer;
55  import org.eclipse.ui.internal.LayoutPart;
56  import org.eclipse.ui.internal.PartSite;
57  import org.eclipse.ui.internal.PartTabFolder;
58  import org.eclipse.ui.part.ViewPart;
59  
60  import com.port80.eclipse.jdt.IConstants;
61  import com.port80.eclipse.jdt.JdtPlugin;
62  import com.port80.eclipse.jdt.Util;
63  import com.port80.eclipse.jdt.actions.ShowInEditorAction;
64  import com.port80.eclipse.jdt.annotation.AnnotationView;
65  import com.port80.eclipse.jdt.util.JavaElementItem;
66  import com.port80.eclipse.jdt.util.JavaElementTypeComparator;
67  import com.port80.eclipse.jdt.util.JavaUtil;
68  import com.port80.eclipse.util.IncrementalFindTreeTarget;
69  import com.port80.eclipse.util.UtilPluginImages;
70  
71  /**
72   * Show methods of a type including methods inherited from super classes.
73   * 
74   * This is similar to the Outline view except that it shows only methods and 
75   * it shows non-private methods from the super classes even though they 
76   * are not overriden.  So user can knows what methods are available.
77   * 
78   * This sample class demonstrates how to plug-in a new
79   * workbench view. The view shows data obtained from the
80   * model. The sample creates a dummy model on the fly,
81   * but a real implementation would connect to the model
82   * available either in this or another plug-in (e.g. the workspace).
83   * The view is connected to the model using a content provider.
84   * <p>
85   * The view uses a label provider to define how model
86   * objects should be presented in the view. Each
87   * view can present the same model objects using
88   * different labels and icons, if needed. Alternatively,
89   * a single label provider can be shared between views
90   * in order to ensure that objects of the same type are
91   * presented in the same way everywhere.
92   * <p>
93   */
94  public class MethodView extends ViewPart implements KeyListener, ISelectionListener, IPropertyChangeListener {
95  
96    ////////////////////////////////////////////////////////////////////////
97  
98    private static final String NAME = "MethodView";
99    private static final String VERSION = "v0.1";
100   private static final String ID = "com.port80.eclipse.jdt.method.MethodView";
101   private static final boolean DEBUG = false;
102 
103   private TreeViewer fViewer;
104   private MethodViewContentProvider provider;
105   private IPartListener partListener;
106   private IType currentType;
107   private Clipboard clipboard;
108   private int fShowLevel;
109   //
110   private Action fActionHeader;
111   private Action fActionShowPublic;
112   private Action fActionShowProtected;
113   private Action fActionShowDefault;
114   private Action fActionShowAll;
115   private Action fActionAnnotate;
116   private Action fActionCopy;
117   private Action fActionRefresh;
118   private Action fActionAbout;
119   //
120   private IncrementalFindTreeTarget findTarget;
121   private boolean fSupressSelectionLinking;
122   private JavaElementTypeComparator typeComparator = new JavaElementTypeComparator();
123   //
124   ShowInEditorAction fActionShowInEditor;
125 
126   ////////////////////////////////////////////////////////////////////////
127 
128   /**
129    * The constructor.
130    */
131   public MethodView() {
132     fShowLevel = MethodViewContentProvider.SHOW_ALL;
133   }
134 
135   ////////////////////////////////////////////////////////////////////////
136 
137   public void init(IViewSite site, IMemento memento) throws PartInitException {
138     super.init(site, memento);
139     if (memento != null) {
140       Integer level = memento.getInteger("ShowLevel");
141       if (level != null)
142         fShowLevel = level.intValue();
143     }
144     //NOTE:   init() is called before createPartControl(), so provider is still null.
145     //    In order to restore state of the provider, it is created here.
146     provider = new MethodViewContentProvider();
147     provider.setShowLevel(fShowLevel);
148   }
149 
150   /**
151    * @see IWorkbenchPart#dispose()
152    */
153   public void dispose() {
154     if (fViewer != null) {
155       getViewSite().getPage().removePartListener(partListener);
156       JdtPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
157       disableSyncSelection();
158     }
159     super.dispose();
160     fViewer = null;
161   }
162 
163   /**
164    * This is a callback that will allow us to create the viewer and initialize it.
165    */
166   public void createPartControl(Composite parent) {
167     fViewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
168     clipboard = new Clipboard(parent.getDisplay());
169     fViewer.setContentProvider(provider);
170     fViewer.setLabelProvider(provider);
171     fViewer.setInput(ResourcesPlugin.getWorkspace());
172     getViewSite().setSelectionProvider(fViewer);
173     makeActions();
174     hookContextMenu();
175     hookDoubleClickAction();
176     hookPartListener();
177     hookKeyListener();
178     contributeToActionBars();
179     IPreferenceStore prefs = JdtPlugin.getDefault().getPreferenceStore();
180     if (prefs.getBoolean(IConstants.PREF_METHODVIEW_SYNC_FROM_EDITOR))
181       enableSyncSelection();
182     prefs.addPropertyChangeListener(this);
183   }
184 
185   /**
186    * Passing the focus request to the viewer's control.
187    */
188   public void setFocus() {
189     fViewer.getControl().setFocus();
190   }
191 
192   public void saveState(IMemento memento) {
193     //NOTE: memento is already a child created for this view <view id=this>
194     memento.putInteger("ShowLevel", fShowLevel);
195   }
196 
197   /**
198    * @param type Show methods of this given type.
199    */
200   public void setInputElement(IType type) {
201     if (type == null
202       || (currentType != null
203         && type.getFullyQualifiedName().equals(currentType.getFullyQualifiedName())))
204       return;
205     gotoObject(type);
206   }
207 
208   public TreeViewer getViewer() {
209     return fViewer;
210   }
211 
212   // INavigateListener interface /////////////////////////////////////
213 
214   public void gotoObject(Object a) {
215     if (a == null)
216       return;
217     if (!(a instanceof IType))
218       return;
219     if (provider.getRoot().getElement() == a)
220       return;
221     IType type = (IType) a;
222     fViewer.collapseAll();
223     provider.setInput(type);
224     currentType = type;
225     // Added folders are collapsed by default, expand interesting ones.
226     // NOTE: Need to refresh() before expandTree(), otherwise, collapsing to object do not work.
227     fViewer.refresh();
228     provider.expandTree(fViewer);
229     fViewer.reveal(provider.getTop());
230   }
231 
232   ////////////////////////////////////////////////////////////////////////
233 
234   private void makeActions() {
235     fActionShowInEditor = new ShowInEditorAction();
236     //
237     fActionHeader = new Action() {
238       public void run() {
239       }
240     };
241     fActionHeader.setText("Method Menu:");
242     fActionHeader.setEnabled(false);
243     //
244     fActionAnnotate = new Action() {
245       public void run() {
246         annotateAction();
247       }
248     };
249     fActionAnnotate.setText("Annotate");
250     fActionAnnotate.setToolTipText("Annotate");
251     fActionAnnotate.setImageDescriptor(
252       PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
253         ISharedImages.IMG_OBJS_TASK_TSK));
254     //
255     fActionShowPublic = new Action() {
256       public void run() {
257         showPublicAction();
258       }
259     };
260     fActionShowPublic.setText("Show public");
261     fActionShowPublic.setToolTipText("Show public methods only");
262     fActionShowPublic.setImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC);
263     //
264     fActionShowProtected = new Action() {
265       public void run() {
266         showProtectedAction();
267       }
268     };
269     fActionShowProtected.setText("Show protected");
270     fActionShowProtected.setToolTipText("Show protected accessable or above");
271     fActionShowProtected.setImageDescriptor(JavaPluginImages.DESC_MISC_PROTECTED);
272     //
273     fActionShowDefault = new Action() {
274       public void run() {
275         showDefaultAction();
276       }
277     };
278     fActionShowDefault.setText("Show package");
279     fActionShowDefault.setToolTipText("Show package accessable or above");
280     fActionShowDefault.setImageDescriptor(JavaPluginImages.DESC_MISC_DEFAULT);
281     //
282     fActionShowAll = new Action() {
283       public void run() {
284         showAllAction();
285       }
286     };
287     fActionShowAll.setText("Show All");
288     fActionShowAll.setToolTipText("Show all methods");
289     fActionShowAll.setImageDescriptor(JavaPluginImages.DESC_MISC_PRIVATE);
290     //
291     fActionCopy = new Action() {
292       public void run() {
293         copyAction();
294       }
295     };
296     fActionCopy.setText("Copy");
297     fActionCopy.setToolTipText("Copy item name to clipboard");
298     fActionCopy.setImageDescriptor(
299       PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_FILE));
300     //
301     fActionRefresh = new Action() {
302       public void run() {
303         refreshAction();
304       }
305     };
306     fActionRefresh.setText("Refresh");
307     fActionRefresh.setToolTipText("Refresh");
308     UtilPluginImages.setLocalImageDescriptors(fActionRefresh, UtilPluginImages.IMG_REFRESH);
309     //
310     fActionAbout = new Action() {
311       public void run() {
312         showMessage(NAME + " " + VERSION);
313       }
314     };
315     fActionAbout.setText("About");
316     fActionAbout.setToolTipText("About MethodView");
317     fActionAbout.setImageDescriptor(
318       PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
319         ISharedImages.IMG_OBJS_INFO_TSK));
320   }
321   private void contributeToActionBars() {
322     IActionBars bars = getViewSite().getActionBars();
323     fillLocalPullDown(bars.getMenuManager());
324     fillLocalToolBar(bars.getToolBarManager());
325   }
326   private void fillLocalPullDown(IMenuManager manager) {
327     manager.add(fActionAbout);
328   }
329   private void fillLocalToolBar(IToolBarManager manager) {
330     manager.add(fActionAnnotate);
331     manager.add(fActionCopy);
332     manager.add(new Separator());
333     manager.add(fActionRefresh);
334     manager.add(new Separator());
335     manager.add(fActionShowPublic);
336     manager.add(fActionShowProtected);
337     manager.add(fActionShowDefault);
338     manager.add(fActionShowAll);
339     manager.add(new Separator());
340     //JdtPlugin.getNavHistory().addNavigationActions(manager);
341     manager.add(new Separator());
342   }
343   private void hookContextMenu() {
344     MenuManager menuMgr = new MenuManager("#PopupMenu");
345     menuMgr.setRemoveAllWhenShown(true);
346     menuMgr.addMenuListener(new IMenuListener() {
347       public void menuAboutToShow(IMenuManager manager) {
348         MethodView.this.fillContextMenu(manager);
349       }
350     });
351     Menu menu = menuMgr.createContextMenu(fViewer.getControl());
352     fViewer.getControl().setMenu(menu);
353     // Register menu so that other plugin can contribute to it.
354     getSite().registerContextMenu(menuMgr, fViewer);
355   }
356   void fillContextMenu(IMenuManager manager) {
357     manager.add(fActionHeader);
358     manager.add(new Separator());
359     manager.add(fActionAnnotate);
360     manager.add(fActionCopy);
361     // Other plug-ins can contribute there actions here
362     manager.add(new Separator("Additions"));
363   }
364   private void hookDoubleClickAction() {
365     fViewer.addDoubleClickListener(new IDoubleClickListener() {
366       public void doubleClick(DoubleClickEvent event) {
367         fActionShowInEditor.run();
368       }
369     });
370   }
371 
372   /** Listen to any part activation and update the method view if an editor part is activated. */
373   private void hookPartListener() {
374     partListener = new IPartListener() {
375       public void partActivated(IWorkbenchPart part) {
376         if (part == null)
377           return;
378         IWorkbenchPartSite site = part.getSite();
379         if (site == null)
380           return;
381         if (part instanceof IEditorPart) {
382           if (methodViewIsOnTop()) {
383             setSelectionFromEditor(part);
384           }
385         } else if (part instanceof MethodView) {
386           part = JdtPlugin.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
387           if (part == null)
388             return;
389           setSelectionFromEditor(part);
390         }
391       }
392       //TELLME: It seems more reasonable to use this instead of partActivated()
393       //    But unfortunately, this is not called when clicking the tab to bring
394       //    Editor to top.
395       public void partBroughtToTop(IWorkbenchPart part) {
396       }
397       public void partClosed(IWorkbenchPart part) {
398       }
399       public void partDeactivated(IWorkbenchPart part) {
400       }
401       public void partOpened(IWorkbenchPart part) {
402       }
403     };
404     getViewSite().getPage().addPartListener(partListener);
405   }
406 
407   boolean methodViewIsOnTop() {
408     PartSite site = (PartSite) getSite();
409     ILayoutContainer container = site.getPane().getContainer();
410     if (container instanceof PartTabFolder) {
411       PartTabFolder folder = (PartTabFolder) container;
412       LayoutPart part = folder.getVisiblePart();
413       if (part != null && part.getID().equals(ID))
414         return true;
415     }
416     return false;
417   }
418 
419   /** Temporary hack to do the incremental search.  Should move to StructuredViewer later.              */
420   private void hookKeyListener() {
421     fViewer.getControl().addKeyListener(this);
422   }
423 
424   void showMessage(String message) {
425     MessageDialog.openInformation(fViewer.getControl().getShell(), NAME, message);
426   }
427 
428   // Actions /////////////////////////////////////////////////////////////
429   //
430 
431   void showPublicAction() {
432     fShowLevel = MethodViewContentProvider.SHOW_PUBLIC;
433     provider.setShowLevel(fShowLevel);
434     gotoObject(currentType);
435   }
436 
437   void showProtectedAction() {
438     fShowLevel = MethodViewContentProvider.SHOW_PROTECTED;
439     provider.setShowLevel(fShowLevel);
440     gotoObject(currentType);
441   }
442 
443   void showDefaultAction() {
444     fShowLevel = MethodViewContentProvider.SHOW_DEFAULT;
445     provider.setShowLevel(fShowLevel);
446     gotoObject(currentType);
447   }
448 
449   void showAllAction() {
450     fShowLevel = MethodViewContentProvider.SHOW_ALL;
451     provider.setShowLevel(fShowLevel);
452     gotoObject(currentType);
453   }
454 
455   void copyAction() {
456     if (currentType == null)
457       return;
458     String text = getSelectedItemText();
459     if (text == null)
460       return;
461     if (DEBUG)
462       System.out.println(NAME + ".copyAction(): text=" + text);
463     try {
464       clipboard.setContents(new Object[] { text }, new Transfer[] { TextTransfer.getInstance()});
465     } catch (SWTError e) {
466       if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD)
467         throw e;
468     }
469   }
470 
471   void refreshAction() {
472     if (currentType == null)
473       return;
474     gotoObject(currentType);
475   }
476 
477   void annotateAction() {
478     JavaElementItem a = (JavaElementItem) getSelection().getFirstElement();
479     if (a == null)
480       return;
481     IJavaElement element = a.getElement();
482     AnnotationView viewer = (AnnotationView) JavaPlugin.getActivePage().findView(AnnotationView.ID);
483     if (viewer == null) {
484       try {
485         viewer=(AnnotationView)JavaPlugin.getActivePage().showView(AnnotationView.ID);
486       } catch (PartInitException e) {
487         JdtPlugin.log("Can't open AnnotationView", e);
488         showMessage("To edit Annotations, please open a AnnotationView first.");
489         return;
490       }
491     }
492     viewer.addAnnotation(element);
493   }
494 
495   private String getSelectedItemText() {
496     //IViewPart view = JavaPlugin.getActivePage().findView(ID_METHODVIEW);
497     if (fViewer == null)
498       return null;
499     IStructuredSelection selection = getSelection();
500     String typename = currentType.getFullyQualifiedName();
501     if (selection == null || selection.isEmpty())
502       return typename;
503     Object a = selection.getFirstElement();
504     Assert.isTrue(a instanceof JavaElementItem, "selection not a JavaElementItem");
505     IJavaElement element = ((JavaElementItem) a).getElement();
506     if (element instanceof IType)
507       return ((IType) element).getFullyQualifiedName();
508     else if (element instanceof IMethod) {
509       IMethod method = (IMethod) element;
510       try {
511         return (
512           Signature.toString(method.getReturnType())
513             + " "
514             + typename
515             + "."
516             + Util.getMethodSignature(method));
517       } catch (JavaModelException e) {
518         JavaPlugin.log(
519           new Status(IStatus.ERROR, "com.port80.eclipse.jdt", 1, "method=" + method, e));
520       }
521     }
522     return typename;
523   }
524 
525   private IStructuredSelection getSelection() {
526     return (IStructuredSelection) fViewer.getSelection();
527   }
528 
529   // ISelectionListener //////////////////////////////////////////////////
530 
531   /**
532    * @see ISelectionListener#selectionChanged(IWorkbenchPart, ISelection)
533    */
534   public void selectionChanged(IWorkbenchPart part, ISelection selection) {
535     if (part instanceof IEditorPart) {
536       if (methodViewIsOnTop()) {
537         if (selection == null || selection.isEmpty())
538           return;
539         if (((ITextSelection) selection).getLength() == 0)
540           return;
541         setSelectionFromEditor(part);
542       }
543     }
544   }
545 
546   // IPropertyChangeListener /////////////////////////////////////////////
547 
548   /**
549    * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
550    */
551   public void propertyChange(PropertyChangeEvent event) {
552     if (IConstants.PREF_METHODVIEW_SYNC_FROM_EDITOR.equals(event.getProperty())) {
553       Boolean enable = (Boolean) event.getNewValue();
554       if (enable.booleanValue())
555         enableSyncSelection();
556       else
557         disableSyncSelection();
558     }
559   }
560 
561   private void enableSyncSelection() {
562     getViewSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this);
563   }
564 
565   private void disableSyncSelection() {
566     getViewSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
567   }
568 
569   // KeyListener ///////////////////////////////////////////////////////
570 
571   public void keyPressed(KeyEvent event) {
572     if (DEBUG)
573       System.out.println(
574         NAME
575           + ".keyPressed(): mask="
576           + event.stateMask
577           + ", character="
578           + event.character
579           + ", keycode="
580           + event.keyCode);
581     // if (event.stateMask == (SWT.CTRL | SWT.ALT | SWT.SHIFT) && event.character == 0x73) {
582     if (event.stateMask == 0 && event.character == 0x73) {
583       // 'C-s' is trapped by eclipse. For now, use 'M-C-s' instead.
584       beginSession(true);
585     } else if (event.stateMask == 0 && event.character == 0x72) {
586       // 'C-r' keyPressed() for 'M-C-r'  are trapped by eclipse. For now, use 'M-C-r' keyReleased() instead.
587       beginSession(false);
588     }
589   }
590   public void keyReleased(KeyEvent event) {
591     if (DEBUG)
592       System.out.println(
593         NAME
594           + ".keyReleased(): mask="
595           + event.stateMask
596           + ", character="
597           + event.character
598           + ", keycode="
599           + event.keyCode);
600     // if (event.stateMask == (SWT.CTRL | SWT.ALT | SWT.SHIFT) && event.character == 0x72) {
601   }
602 
603   public void beginSession(boolean forward) {
604     findTarget =
605       new IncrementalFindTreeTarget(
606         fViewer,
607         getViewSite().getActionBars().getStatusLineManager(),
608         this);
609     String defaultString = null;
610     IStructuredSelection selection = getSelection();
611     if (selection != null && !selection.isEmpty()) {
612       Object a = selection.getFirstElement();
613       IJavaElement element = ((JavaElementItem) a).getElement();
614       defaultString = element.getElementName();
615     }
616     findTarget.beginSession(forward, defaultString);
617   }
618 
619   // Update Method View on editor activation /////////////////////
620 
621   public void setSelection(ISelection selection, boolean reveal) {
622     if (selection != null && selection.equals(fViewer.getSelection()))
623       return;
624     fViewer.setSelection(selection, reveal);
625   }
626 
627   void setSelectionFromEditor(IWorkbenchPart part) {
628     if (DEBUG)
629       System.err.println(NAME + ".setSelectionFromEditor(): part=" + part);
630     IJavaElement element = JavaUtil.getSelectedElementFromEditor(part);
631     if (element != null)
632       adjustInputAndSetSelection(element);
633   }
634 
635   /**
636    * Update view input and selection to the specified Java element.
637    */
638   private void adjustInputAndSetSelection(IJavaElement je) {
639     try {
640       if (DEBUG)
641         System.err.println(errorMessage(".adjustInputAndSetSelection()", je));
642       IJavaElement elementToSelect = findSelectableElement(je);
643       IType newInput = findInputForElement(je);
644       if (DEBUG) {
645         System.err.println(NAME + ".adjustInputAndSetSelection(): ");
646         if (elementToSelect != null)
647           System.err.println("\tselect=" + elementToSelect.getElementName());
648         if (newInput != null)
649           System.err.println("\tnewInput=" + newInput.getElementName());
650       }
651       setInputElement(newInput);
652       StructuredSelection selection = null;
653       if (elementToSelect != null) {
654         JavaElementItem item = provider.findItem(elementToSelect);
655         if (item != null)
656           selection = new StructuredSelection(item);
657       }
658       if (selection != null)
659         setSelection(selection, true);
660       else {
661         fViewer.reveal(provider.getRoot());
662       }
663     } catch (Exception e) {
664       System.err.println(NAME + ".adjustInputAndSetSelection(): " + e);
665       e.printStackTrace();
666     }
667   }
668   /**
669    * @return A selectable Java element in MethodView (IMethod or IType) that enclose the given Java element.
670    */
671   protected IJavaElement findSelectableElement(IJavaElement element) {
672     String message = ".findSelectableElement()";
673     int type = element.getElementType();
674     if (type < IJavaElement.COMPILATION_UNIT)
675       return null;
676     if (type > IJavaElement.METHOD || type == IJavaElement.FIELD)
677       return findSelectableElement(element.getParent());
678     try {
679       switch (type) {
680         case IJavaElement.COMPILATION_UNIT :
681           message = message + ": COMPILATION_UNIT";
682           return ((ICompilationUnit) element).getTypes()[0];
683         case IJavaElement.CLASS_FILE :
684           message = message + ": CLASS_FILE";
685           return ((IClassFile) element).getType();
686         case IJavaElement.TYPE :
687           return element;
688         case IJavaElement.METHOD :
689           return element;
690         default :
691           System.err.println(errorMessage(message, element));
692       }
693     } catch (Exception e) {
694       JavaPlugin.log(
695         new Status(
696           IStatus.ERROR,
697           "com.port80.eclipse.jdt",
698           1,
699           errorMessage(message, element),
700           e));
701     }
702     return null;
703   }
704   /**
705    * Converts the given Java element to one which is suitable for this
706    * view as input. It takes into account wether the view shows working copies or not.
707    * 
708    * @param       je      the Java element for which to search the closest input
709    * @return      the closest Java element used as input for this part
710    */
711   protected IType findInputForElement(IJavaElement element) {
712     if (DEBUG)
713       System.err.println(errorMessage(".findInputForElement()", element));
714     int type = element.getElementType();
715     if (type < IJavaElement.COMPILATION_UNIT)
716       return null;
717     if (type > IJavaElement.TYPE)
718       return findInputForElement(element.getParent());
719     String message = ".getTypeForElement()";
720     try {
721       if (type == IJavaElement.TYPE)
722         return (IType) element;
723       if (type == IJavaElement.COMPILATION_UNIT) {
724         message = message + ": COMPILATION_UNIT";
725         return ((ICompilationUnit) element).getTypes()[0];
726       }
727       if (type == IJavaElement.CLASS_FILE) {
728         message = message + ": CLASS_FILE";
729         return ((IClassFile) element).getType();
730       }
731       System.err.println(errorMessage(message + ": Invalid element", element));
732     } catch (Exception e) {
733       JavaPlugin.log(
734         new Status(
735           IStatus.ERROR,
736           "com.port80.eclipse.jdt",
737           1,
738           errorMessage(message, element),
739           e));
740     }
741 
742     //
743     // This is an ICompilationUnit.
744     //                if (((BaseJavaElementContentProvider) fViewer.getContentProvider()).getProvideWorkingCopy()) {
745     //                        IJavaElement wc= getWorkingCopy(element);
746     //                        if (wc != null)
747     //                                element= wc;
748     //                } else {
749     //                        ICompilationUnit cu= getCompilationUnit(element);
750     //                        if (cu != null && ((IWorkingCopy) cu).isWorkingCopy())
751     //                                element= ((IWorkingCopy) cu).getOriginal(element);
752     //                }
753     //                if (element.getElementType() == IJavaElement.COMPILATION_UNIT)
754     //                        try {
755     //                                return ((ICompilationUnit) element).getTypes()[0];
756     //                        } catch (Exception e) {
757     //                                JavaPlugin.log(e);
758     //                        }
759     return null;
760   }
761 
762   /**
763    * Answers if the given <code>element</code> is a valid
764    * element for this part.  For MethodView only IType is valid.
765    * 
766    * @param       element the object to test
767    * @return      <true> if the given element is a valid element
768    */
769   protected boolean isValidInput(Object element) {
770     if (element == null)
771       return false;
772     return (element instanceof IType);
773   }
774 
775   /** Return an error message for the given Java element.*/
776   private String errorMessage(String method, IJavaElement e) {
777     String ret = NAME + method;
778     String name = null;
779     int type = 0;
780     if (e != null) {
781       name = e.getElementName();
782       type = e.getElementType();
783     }
784     if (name != null)
785       return ret + ": element=" + name + ", type=" + type;
786     else
787       return ret;
788   }
789 
790   ////////////////////////////////////////////////////////////////////////
791   //        /**
792   //         * Returns the compilation unit for the given java element.
793   //         *
794   //         * @param       element the java element whose compilation unit is searched for
795   //         * @return      the compilation unit of the given java element
796   //         */
797   //        protected static ICompilationUnit getCompilationUnit(IJavaElement element) {
798   //                if (element == null)
799   //                        return null;
800   //
801   //                if (element instanceof IMember)
802   //                        return ((IMember) element).getCompilationUnit();
803   //
804   //                int type= element.getElementType();
805   //                if (IJavaElement.COMPILATION_UNIT == type)
806   //                        return (ICompilationUnit) element;
807   //                if (IJavaElement.CLASS_FILE == type)
808   //                        return null;
809   //
810   //                return getCompilationUnit(element.getParent());
811   //        }
812   //
813   //        /**
814   //         * Tries to find the given element in a workingcopy.
815   //         */
816   //        protected static IJavaElement getWorkingCopy(IJavaElement input) {
817   //                try {
818   //                        if (input instanceof ICompilationUnit)
819   //                                return EditorUtility.getWorkingCopy((ICompilationUnit) input);
820   //                        else
821   //                                return EditorUtility.getWorkingCopy(input, true);
822   //                } catch (JavaModelException ex) {}
823   //                return null;
824   //        }
825   //
826   //        /**
827   //         * Returns the original element from which the specified working copy
828   //         * element was created from. This is a handle only method, the
829   //         * returned element may or may not exist.
830   //         *
831   //         * @param       workingCopy the element for which to get the original
832   //         * @return the original Java element or <code>null</code> if this is not a working copy element
833   //         */
834   //        protected static IJavaElement getOriginal(IJavaElement workingCopy) {
835   //                ICompilationUnit cu= getCompilationUnit(workingCopy);
836   //                if (cu != null)
837   //                        return ((IWorkingCopy) cu).getOriginal(workingCopy);
838   //                return null;
839   //        }
840   ////////////////////////////////////////////////////////////////////////
841 }