KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > packageview > PackageExplorerPart


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.jdt.internal.ui.packageview;
12
13 import java.io.IOException JavaDoc;
14 import java.io.StringReader JavaDoc;
15 import java.io.StringWriter JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.Collections JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20
21 import org.eclipse.core.runtime.CoreException;
22 import org.eclipse.core.runtime.IAdaptable;
23 import org.eclipse.core.runtime.IPath;
24 import org.eclipse.core.runtime.ISafeRunnable;
25 import org.eclipse.core.runtime.IStatus;
26 import org.eclipse.core.runtime.PerformanceStats;
27 import org.eclipse.core.runtime.SafeRunner;
28
29 import org.eclipse.core.resources.IContainer;
30 import org.eclipse.core.resources.IFile;
31 import org.eclipse.core.resources.IProject;
32 import org.eclipse.core.resources.IResource;
33 import org.eclipse.core.resources.IWorkspace;
34 import org.eclipse.core.resources.ResourcesPlugin;
35
36 import org.eclipse.swt.SWT;
37 import org.eclipse.swt.dnd.DND;
38 import org.eclipse.swt.dnd.FileTransfer;
39 import org.eclipse.swt.dnd.Transfer;
40 import org.eclipse.swt.events.KeyAdapter;
41 import org.eclipse.swt.events.KeyEvent;
42 import org.eclipse.swt.widgets.Composite;
43 import org.eclipse.swt.widgets.Control;
44 import org.eclipse.swt.widgets.Item;
45 import org.eclipse.swt.widgets.Menu;
46 import org.eclipse.swt.widgets.TreeItem;
47 import org.eclipse.swt.widgets.Widget;
48
49 import org.eclipse.help.IContextProvider;
50
51 import org.eclipse.jface.action.IMenuListener;
52 import org.eclipse.jface.action.IMenuManager;
53 import org.eclipse.jface.action.IStatusLineManager;
54 import org.eclipse.jface.action.MenuManager;
55 import org.eclipse.jface.dialogs.IDialogSettings;
56 import org.eclipse.jface.dialogs.MessageDialog;
57 import org.eclipse.jface.preference.IPreferenceStore;
58 import org.eclipse.jface.util.IPropertyChangeListener;
59 import org.eclipse.jface.util.PropertyChangeEvent;
60 import org.eclipse.jface.util.TransferDragSourceListener;
61 import org.eclipse.jface.util.TransferDropTargetListener;
62 import org.eclipse.jface.viewers.AbstractTreeViewer;
63 import org.eclipse.jface.viewers.DoubleClickEvent;
64 import org.eclipse.jface.viewers.IContentProvider;
65 import org.eclipse.jface.viewers.IDoubleClickListener;
66 import org.eclipse.jface.viewers.IElementComparer;
67 import org.eclipse.jface.viewers.ILabelDecorator;
68 import org.eclipse.jface.viewers.IOpenListener;
69 import org.eclipse.jface.viewers.ISelection;
70 import org.eclipse.jface.viewers.ISelectionChangedListener;
71 import org.eclipse.jface.viewers.ISelectionProvider;
72 import org.eclipse.jface.viewers.IStructuredSelection;
73 import org.eclipse.jface.viewers.ITreeSelection;
74 import org.eclipse.jface.viewers.ITreeViewerListener;
75 import org.eclipse.jface.viewers.OpenEvent;
76 import org.eclipse.jface.viewers.SelectionChangedEvent;
77 import org.eclipse.jface.viewers.StructuredSelection;
78 import org.eclipse.jface.viewers.TreeExpansionEvent;
79 import org.eclipse.jface.viewers.TreePath;
80 import org.eclipse.jface.viewers.TreeViewer;
81 import org.eclipse.jface.viewers.ViewerFilter;
82
83 import org.eclipse.ui.IActionBars;
84 import org.eclipse.ui.IEditorInput;
85 import org.eclipse.ui.IEditorPart;
86 import org.eclipse.ui.IEditorReference;
87 import org.eclipse.ui.IMemento;
88 import org.eclipse.ui.IPageLayout;
89 import org.eclipse.ui.IPartListener2;
90 import org.eclipse.ui.IStorageEditorInput;
91 import org.eclipse.ui.IViewPart;
92 import org.eclipse.ui.IViewSite;
93 import org.eclipse.ui.IWorkbenchPage;
94 import org.eclipse.ui.IWorkbenchPartReference;
95 import org.eclipse.ui.IWorkbenchPartSite;
96 import org.eclipse.ui.IWorkingSet;
97 import org.eclipse.ui.PartInitException;
98 import org.eclipse.ui.WorkbenchException;
99 import org.eclipse.ui.XMLMemento;
100 import org.eclipse.ui.actions.ActionContext;
101 import org.eclipse.ui.part.ISetSelectionTarget;
102 import org.eclipse.ui.part.IShowInSource;
103 import org.eclipse.ui.part.IShowInTarget;
104 import org.eclipse.ui.part.IShowInTargetList;
105 import org.eclipse.ui.part.ResourceTransfer;
106 import org.eclipse.ui.part.ShowInContext;
107 import org.eclipse.ui.part.ViewPart;
108
109 import org.eclipse.ui.views.framelist.Frame;
110 import org.eclipse.ui.views.framelist.FrameAction;
111 import org.eclipse.ui.views.framelist.FrameList;
112 import org.eclipse.ui.views.framelist.IFrameSource;
113 import org.eclipse.ui.views.framelist.TreeFrame;
114 import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
115
116 import org.eclipse.jdt.core.IClassFile;
117 import org.eclipse.jdt.core.ICompilationUnit;
118 import org.eclipse.jdt.core.IJarEntryResource;
119 import org.eclipse.jdt.core.IJavaElement;
120 import org.eclipse.jdt.core.IJavaModel;
121 import org.eclipse.jdt.core.IJavaProject;
122 import org.eclipse.jdt.core.IPackageFragment;
123 import org.eclipse.jdt.core.IPackageFragmentRoot;
124 import org.eclipse.jdt.core.IType;
125 import org.eclipse.jdt.core.JavaCore;
126 import org.eclipse.jdt.core.JavaModelException;
127
128 import org.eclipse.jdt.internal.corext.util.Messages;
129
130 import org.eclipse.jdt.ui.IPackagesViewPart;
131 import org.eclipse.jdt.ui.JavaElementComparator;
132 import org.eclipse.jdt.ui.JavaElementLabels;
133 import org.eclipse.jdt.ui.JavaUI;
134 import org.eclipse.jdt.ui.PreferenceConstants;
135 import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
136 import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup;
137
138 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
139 import org.eclipse.jdt.internal.ui.JavaPlugin;
140 import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
141 import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
142 import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
143 import org.eclipse.jdt.internal.ui.filters.OutputFolderFilter;
144 import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
145 import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
146 import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
147 import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
148 import org.eclipse.jdt.internal.ui.viewsupport.ColoredViewersManager;
149 import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
150 import org.eclipse.jdt.internal.ui.viewsupport.FilterUpdater;
151 import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
152 import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
153 import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
154 import org.eclipse.jdt.internal.ui.workingsets.ConfigureWorkingSetAction;
155 import org.eclipse.jdt.internal.ui.workingsets.ViewActionGroup;
156 import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
157 import org.eclipse.jdt.internal.ui.workingsets.WorkingSetModel;
158  
159 /**
160  * The ViewPart for the ProjectExplorer. It listens to part activation events.
161  * When selection linking with the editor is enabled the view selection tracks
162  * the active editor page. Similarly when a resource is selected in the packages
163  * view the corresponding editor is activated.
164  */

165  
166 public class PackageExplorerPart extends ViewPart
167     implements ISetSelectionTarget, IMenuListener,
168         IShowInTarget,
169         IPackagesViewPart, IPropertyChangeListener,
170         IViewPartInputProvider {
171     
172     private static final String JavaDoc PERF_CREATE_PART_CONTROL= "org.eclipse.jdt.ui/perf/explorer/createPartControl"; //$NON-NLS-1$
173
private static final String JavaDoc PERF_MAKE_ACTIONS= "org.eclipse.jdt.ui/perf/explorer/makeActions"; //$NON-NLS-1$
174

175     private static final int HIERARCHICAL_LAYOUT= 0x1;
176     private static final int FLAT_LAYOUT= 0x2;
177     
178     private final static String JavaDoc VIEW_ID= JavaUI.ID_PACKAGES;
179                 
180     // Persistence tags.
181
private static final String JavaDoc TAG_LAYOUT= "layout"; //$NON-NLS-1$
182
private static final String JavaDoc TAG_GROUP_LIBRARIES= "group_libraries"; //$NON-NLS-1$
183
private static final String JavaDoc TAG_ROOT_MODE= "rootMode"; //$NON-NLS-1$
184
private static final String JavaDoc TAG_LINK_EDITOR= "linkWithEditor"; //$NON-NLS-1$
185
private static final String JavaDoc TAG_MEMENTO= "memento"; //$NON-NLS-1$
186

187     private boolean fIsCurrentLayoutFlat; // true means flat, false means hierarchical
188
private boolean fShowLibrariesNode;
189     private boolean fLinkingEnabled;
190     
191     private int fRootMode;
192     private WorkingSetModel fWorkingSetModel;
193     
194     private PackageExplorerLabelProvider fLabelProvider;
195     private DecoratingJavaLabelProvider fDecoratingLabelProvider;
196     private PackageExplorerContentProvider fContentProvider;
197     private FilterUpdater fFilterUpdater;
198     
199     private PackageExplorerActionGroup fActionSet;
200     private ProblemTreeViewer fViewer;
201     private Menu fContextMenu;
202     
203     private IMemento fMemento;
204     
205     private ISelection fLastOpenSelection;
206     private final ISelectionChangedListener fPostSelectionListener;
207     
208     private String JavaDoc fWorkingSetLabel;
209     private IDialogSettings fDialogSettings;
210     
211     
212     private IPartListener2 fLinkWithEditorListener= new IPartListener2() {
213         public void partVisible(IWorkbenchPartReference partRef) {}
214         public void partBroughtToTop(IWorkbenchPartReference partRef) {}
215         public void partClosed(IWorkbenchPartReference partRef) {}
216         public void partDeactivated(IWorkbenchPartReference partRef) {}
217         public void partHidden(IWorkbenchPartReference partRef) {}
218         public void partOpened(IWorkbenchPartReference partRef) {}
219         public void partInputChanged(IWorkbenchPartReference partRef) {
220             if (partRef instanceof IEditorReference) {
221                 editorActivated(((IEditorReference) partRef).getEditor(true));
222             }
223         }
224         
225         public void partActivated(IWorkbenchPartReference partRef) {
226             if (partRef instanceof IEditorReference) {
227                 editorActivated(((IEditorReference) partRef).getEditor(true));
228             }
229         }
230
231     };
232     
233     private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
234         public void treeCollapsed(TreeExpansionEvent event) {
235         }
236         
237         public void treeExpanded(TreeExpansionEvent event) {
238             Object JavaDoc element= event.getElement();
239             if (element instanceof ICompilationUnit ||
240                 element instanceof IClassFile)
241                 expandMainType(element);
242         }
243     };
244
245     private class PackageExplorerProblemTreeViewer extends ProblemTreeViewer {
246         // fix for 64372 Projects showing up in Package Explorer twice [package explorer]
247
private List JavaDoc fPendingRefreshes;
248         
249         public PackageExplorerProblemTreeViewer(Composite parent, int style) {
250             super(parent, style);
251             fPendingRefreshes= Collections.synchronizedList(new ArrayList JavaDoc());
252             ColoredViewersManager.install(this);
253         }
254         public void add(Object JavaDoc parentElement, Object JavaDoc[] childElements) {
255             if (fPendingRefreshes.contains(parentElement)) {
256                 return;
257             }
258             super.add(parentElement, childElements);
259         }
260                         
261         /* (non-Javadoc)
262          * @see org.eclipse.jface.viewers.AbstractTreeViewer#internalRefresh(java.lang.Object, boolean)
263          */

264         protected void internalRefresh(Object JavaDoc element, boolean updateLabels) {
265             try {
266                 fPendingRefreshes.add(element);
267                 super.internalRefresh(element, updateLabels);
268             } finally {
269                 fPendingRefreshes.remove(element);
270             }
271         }
272         
273         protected boolean evaluateExpandableWithFilters(Object JavaDoc parent) {
274             if (parent instanceof IJavaProject
275                     || parent instanceof ICompilationUnit || parent instanceof IClassFile
276                     || parent instanceof ClassPathContainer) {
277                 return false;
278             }
279             if (parent instanceof IPackageFragmentRoot && ((IPackageFragmentRoot) parent).isArchive()) {
280                 return false;
281             }
282             return true;
283         }
284
285         protected boolean isFiltered(Object JavaDoc object, Object JavaDoc parent, ViewerFilter[] filters) {
286             if (object instanceof PackageFragmentRootContainer) {
287                 return !hasFilteredChildren(object);
288             }
289             
290             boolean res= super.isFiltered(object, parent, filters);
291             if (res && isEssential(object)) {
292                 return false;
293             }
294             return res;
295         }
296         
297         /* Checks if a filtered object in essential (i.e. is a parent that
298          * should not be removed).
299          */

300         private boolean isEssential(Object JavaDoc object) {
301             try {
302                 if (!isFlatLayout() && object instanceof IPackageFragment) {
303                     IPackageFragment fragment = (IPackageFragment) object;
304                     if (!fragment.isDefaultPackage() && fragment.hasSubpackages()) {
305                         return hasFilteredChildren(fragment);
306                     }
307                 }
308             } catch (JavaModelException e) {
309                 JavaPlugin.log(e);
310             }
311             return false;
312         }
313         
314         protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) {
315             IStructuredSelection is= (IStructuredSelection)invalidSelection;
316             List JavaDoc ns= null;
317             if (newSelection instanceof IStructuredSelection) {
318                 ns= new ArrayList JavaDoc(((IStructuredSelection)newSelection).toList());
319             } else {
320                 ns= new ArrayList JavaDoc();
321             }
322             boolean changed= false;
323             for (Iterator JavaDoc iter= is.iterator(); iter.hasNext();) {
324                 Object JavaDoc element= iter.next();
325                 if (element instanceof IJavaProject) {
326                     IProject project= ((IJavaProject)element).getProject();
327                     if (!project.isOpen() && project.exists()) {
328                         ns.add(project);
329                         changed= true;
330                     }
331                 } else if (element instanceof IProject) {
332                     IProject project= (IProject)element;
333                     if (project.isOpen()) {
334                         IJavaProject jProject= JavaCore.create(project);
335                         if (jProject != null && jProject.exists())
336                             ns.add(jProject);
337                             changed= true;
338                     }
339                 }
340             }
341             if (changed) {
342                 newSelection= new StructuredSelection(ns);
343                 setSelection(newSelection);
344             }
345             super.handleInvalidSelection(invalidSelection, newSelection);
346         }
347         
348         /**
349          * {@inheritDoc}
350          */

351         protected Object JavaDoc[] addAditionalProblemParents(Object JavaDoc[] elements) {
352             if (showWorkingSets() && elements != null) {
353                 return fWorkingSetModel.addWorkingSets(elements);
354             }
355             return elements;
356         }
357         
358         //---- special handling to preserve the selection correctly
359
private boolean fInPreserveSelection;
360         protected void preservingSelection(Runnable JavaDoc updateCode) {
361             try {
362                 fInPreserveSelection= true;
363                 super.preservingSelection(updateCode);
364             } finally {
365                 fInPreserveSelection= false;
366             }
367         }
368         protected void setSelectionToWidget(ISelection selection, boolean reveal) {
369             if (true) {
370                 super.setSelectionToWidget(selection, reveal);
371                 return;
372             }
373             if (!fInPreserveSelection || !(selection instanceof ITreeSelection)) {
374                 super.setSelectionToWidget(selection, reveal);
375                 return;
376             }
377             IContentProvider cp= getContentProvider();
378             if (!(cp instanceof IMultiElementTreeContentProvider)) {
379                 super.setSelectionToWidget(selection, reveal);
380                 return;
381             }
382             IMultiElementTreeContentProvider contentProvider= (IMultiElementTreeContentProvider)cp;
383             ITreeSelection toRestore= (ITreeSelection)selection;
384             List JavaDoc pathsToSelect= new ArrayList JavaDoc();
385             for (Iterator JavaDoc iter= toRestore.iterator(); iter.hasNext();) {
386                 Object JavaDoc element= iter.next();
387                 TreePath[] pathsToRestore= toRestore.getPathsFor(element);
388                 CustomHashtable currentParents= createRootAccessedMap(contentProvider.getTreePaths(element));
389                 for (int i= 0; i < pathsToRestore.length; i++) {
390                     TreePath path= pathsToRestore[i];
391                     Object JavaDoc root= path.getFirstSegment();
392                     if (root != null && path.equals((TreePath)currentParents.get(root), getComparer())) {
393                         pathsToSelect.add(path);
394                     }
395                 }
396             }
397             List JavaDoc toSelect= new ArrayList JavaDoc();
398             for (Iterator JavaDoc iter= pathsToSelect.iterator(); iter.hasNext();) {
399                 TreePath path= (TreePath)iter.next();
400                 int size= path.getSegmentCount();
401                 if (size == 0)
402                     continue;
403                 Widget current= getTree();
404                 int last= size - 1;
405                 Object JavaDoc segment;
406                 for (int i= 0; i < size && current != null && (segment= path.getSegment(i)) != null; i++) {
407                     internalExpandToLevel(current, 1);
408                     current= internalFindChild(current, segment);
409                     if (i == last && current != null)
410                         toSelect.add(current);
411                 }
412             }
413             getTree().setSelection((TreeItem[])toSelect.toArray(new TreeItem[toSelect.size()]));
414         }
415         private Widget internalFindChild(Widget parent, Object JavaDoc element) {
416             Item[] items = getChildren(parent);
417             for (int i = 0; i < items.length; i++) {
418                 Item item = items[i];
419                 Object JavaDoc data = item.getData();
420                 if (data != null && equals(data, element))
421                     return item;
422             }
423             return null;
424         }
425         private CustomHashtable createRootAccessedMap(TreePath[] paths) {
426             CustomHashtable result= new CustomHashtable(getComparer());
427             for (int i= 0; i < paths.length; i++) {
428                 TreePath path= paths[i];
429                 Object JavaDoc root= path.getFirstSegment();
430                 if (root != null) {
431                     result.put(root, path);
432                 }
433             }
434             return result;
435         }
436     }
437     
438     public PackageExplorerPart() {
439         fPostSelectionListener= new ISelectionChangedListener() {
440             public void selectionChanged(SelectionChangedEvent event) {
441                 handlePostSelectionChanged(event);
442             }
443         };
444         
445         // exception: initialize from preference
446
fDialogSettings= JavaPlugin.getDefault().getDialogSettingsSection(getClass().getName());
447         
448         // on by default
449
fShowLibrariesNode= fDialogSettings.get(TAG_GROUP_LIBRARIES) == null || fDialogSettings.getBoolean(TAG_GROUP_LIBRARIES);
450         
451         fLinkingEnabled= fDialogSettings.getBoolean(TAG_LINK_EDITOR);
452         
453         try {
454             fIsCurrentLayoutFlat= fDialogSettings.getInt(TAG_LAYOUT) == FLAT_LAYOUT;
455         } catch (NumberFormatException JavaDoc e) {
456             fIsCurrentLayoutFlat= true;
457         }
458         
459         try {
460             fRootMode= fDialogSettings.getInt(TAG_ROOT_MODE);
461         } catch (NumberFormatException JavaDoc e) {
462             fRootMode= ViewActionGroup.SHOW_PROJECTS;
463         }
464         
465     }
466     
467     public void init(IViewSite site, IMemento memento) throws PartInitException {
468         super.init(site, memento);
469         if (memento == null) {
470             String JavaDoc persistedMemento= fDialogSettings.get(TAG_MEMENTO);
471             if (persistedMemento != null) {
472                 try {
473                     memento= XMLMemento.createReadRoot(new StringReader JavaDoc(persistedMemento));
474                 } catch (WorkbenchException e) {
475                     // don't do anything. Simply don't restore the settings
476
}
477             }
478         }
479         fMemento= memento;
480         if (memento != null) {
481             restoreLayoutState(memento);
482             restoreLinkingEnabled(memento);
483             restoreRootMode(memento);
484         }
485         if (showWorkingSets()) {
486             createWorkingSetModel();
487         }
488     }
489
490     private void restoreRootMode(IMemento memento) {
491         Integer JavaDoc value= memento.getInteger(TAG_ROOT_MODE);
492         fRootMode= value == null ? ViewActionGroup.SHOW_PROJECTS : value.intValue();
493         if (fRootMode != ViewActionGroup.SHOW_PROJECTS && fRootMode != ViewActionGroup.SHOW_WORKING_SETS)
494             fRootMode= ViewActionGroup.SHOW_PROJECTS;
495     }
496
497     private void restoreLayoutState(IMemento memento) {
498         Integer JavaDoc layoutState= memento.getInteger(TAG_LAYOUT);
499         fIsCurrentLayoutFlat= layoutState == null || layoutState.intValue() == FLAT_LAYOUT;
500         
501         // on by default
502
Integer JavaDoc groupLibraries= memento.getInteger(TAG_GROUP_LIBRARIES);
503         fShowLibrariesNode= groupLibraries == null || groupLibraries.intValue() != 0;
504     }
505     
506     /**
507      * Returns the package explorer part of the active perspective. If
508      * there isn't any package explorer part <code>null</code> is returned.
509      * @return the package explorer from the active perspective
510      */

511     public static PackageExplorerPart getFromActivePerspective() {
512         IWorkbenchPage activePage= JavaPlugin.getActivePage();
513         if (activePage == null)
514             return null;
515         IViewPart view= activePage.findView(VIEW_ID);
516         if (view instanceof PackageExplorerPart)
517             return (PackageExplorerPart)view;
518         return null;
519     }
520     
521     /**
522      * Makes the package explorer part visible in the active perspective. If there
523      * isn't a package explorer part registered <code>null</code> is returned.
524      * Otherwise the opened view part is returned.
525      * @return the opened package explorer
526      */

527     public static PackageExplorerPart openInActivePerspective() {
528         try {
529             return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID);
530         } catch(PartInitException pe) {
531             return null;
532         }
533     }
534         
535      public void dispose() {
536         XMLMemento memento= XMLMemento.createWriteRoot("packageExplorer"); //$NON-NLS-1$
537
saveState(memento);
538         StringWriter JavaDoc writer= new StringWriter JavaDoc();
539         try {
540             memento.save(writer);
541             fDialogSettings.put(TAG_MEMENTO, writer.getBuffer().toString());
542         } catch (IOException JavaDoc e) {
543             // don't do anything. Simply don't store the settings
544
}
545          
546         if (fContextMenu != null && !fContextMenu.isDisposed())
547             fContextMenu.dispose();
548         
549         getSite().getPage().removePartListener(fLinkWithEditorListener); // always remove even if we didn't register
550

551         JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
552         if (fViewer != null) {
553             fViewer.removeTreeListener(fExpansionListener);
554         }
555         
556         if (fActionSet != null)
557             fActionSet.dispose();
558         if (fFilterUpdater != null)
559             ResourcesPlugin.getWorkspace().removeResourceChangeListener(fFilterUpdater);
560         if (fWorkingSetModel != null)
561             fWorkingSetModel.dispose();
562         super.dispose();
563     }
564
565     /* (non-Javadoc)
566      * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
567      */

568     public void createPartControl(Composite parent) {
569
570         final PerformanceStats stats= PerformanceStats.getStats(PERF_CREATE_PART_CONTROL, this);
571         stats.startRun();
572
573         fViewer= createViewer(parent);
574         fViewer.setUseHashlookup(true);
575         
576         initDragAndDrop();
577         
578         setProviders();
579         
580         JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
581     
582         
583         MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
584
menuMgr.setRemoveAllWhenShown(true);
585         menuMgr.addMenuListener(this);
586         fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
587         fViewer.getTree().setMenu(fContextMenu);
588         
589         // Register viewer with site. This must be done before making the actions.
590
IWorkbenchPartSite site= getSite();
591         site.registerContextMenu(menuMgr, fViewer);
592         site.setSelectionProvider(fViewer);
593         
594         makeActions(); // call before registering for selection changes
595

596         // Set input after filter and sorter has been set. This avoids resorting and refiltering.
597
restoreFilterAndSorter();
598         fViewer.setInput(findInputElement());
599         initFrameActions();
600         initKeyListener();
601             
602
603         fViewer.addPostSelectionChangedListener(fPostSelectionListener);
604         
605         fViewer.addDoubleClickListener(new IDoubleClickListener() {
606             public void doubleClick(DoubleClickEvent event) {
607                 fActionSet.handleDoubleClick(event);
608             }
609         });
610         
611         fViewer.addOpenListener(new IOpenListener() {
612             public void open(OpenEvent event) {
613                 fActionSet.handleOpen(event);
614                 fLastOpenSelection= event.getSelection();
615             }
616         });
617
618         IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
619         fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
620         fViewer.addTreeListener(fExpansionListener);
621     
622         // Set help for the view
623
JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW);
624         
625         fillActionBars();
626
627         updateTitle();
628         
629         fFilterUpdater= new FilterUpdater(fViewer);
630         ResourcesPlugin.getWorkspace().addResourceChangeListener(fFilterUpdater);
631         
632         // Sync'ing the package explorer has to be done here. It can't be done
633
// when restoring the link state since the package explorers input isn't
634
// set yet.
635
setLinkingEnabled(isLinkingEnabled());
636         
637         stats.endRun();
638     }
639
640     private void initFrameActions() {
641         fActionSet.getUpAction().update();
642         fActionSet.getBackAction().update();
643         fActionSet.getForwardAction().update();
644     }
645
646     private ProblemTreeViewer createViewer(Composite composite) {
647         return new PackageExplorerProblemTreeViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
648     }
649
650     /**
651      * Answers whether this part shows the packages flat or hierarchical.
652      * @return <true> if flat layout is selected
653      *
654      * @since 2.1
655      */

656     public boolean isFlatLayout() {
657         return fIsCurrentLayoutFlat;
658     }
659     
660     private void setProviders() {
661         //content provider must be set before the label provider
662
fContentProvider= createContentProvider();
663         fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
664         fContentProvider.setShowLibrariesNode(fShowLibrariesNode);
665         fViewer.setContentProvider(fContentProvider);
666
667         fViewer.setComparer(createElementComparer());
668         
669         fLabelProvider= createLabelProvider();
670         fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
671         fDecoratingLabelProvider= new DecoratingJavaLabelProvider(fLabelProvider, false, fIsCurrentLayoutFlat);
672         fViewer.setLabelProvider(fDecoratingLabelProvider);
673         // problem decoration provided by PackageLabelProvider
674
}
675     
676     public void setShowLibrariesNode(boolean enabled) {
677         fShowLibrariesNode= enabled;
678         saveDialogSettings();
679         
680         fContentProvider.setShowLibrariesNode(enabled);
681         fViewer.getControl().setRedraw(false);
682         fViewer.refresh();
683         fViewer.getControl().setRedraw(true);
684     }
685     
686     boolean isLibrariesNodeShown() {
687         return fShowLibrariesNode;
688     }
689     
690     
691     public void setFlatLayout(boolean enable) {
692         // Update current state and inform content and label providers
693
fIsCurrentLayoutFlat= enable;
694         saveDialogSettings();
695         
696         if (fViewer != null) {
697             fContentProvider.setIsFlatLayout(isFlatLayout());
698             fLabelProvider.setIsFlatLayout(isFlatLayout());
699             fDecoratingLabelProvider.setFlatPackageMode(isFlatLayout());
700             
701             fViewer.getControl().setRedraw(false);
702             fViewer.refresh();
703             fViewer.getControl().setRedraw(true);
704         }
705     }
706     
707     /**
708      * This method should only be called inside this class
709      * and from test cases.
710      * @return the created content provider
711      */

712     public PackageExplorerContentProvider createContentProvider() {
713         IPreferenceStore store= PreferenceConstants.getPreferenceStore();
714         boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
715         if (showProjects())
716             return new PackageExplorerContentProvider(showCUChildren);
717         else
718             return new WorkingSetAwareContentProvider(showCUChildren, fWorkingSetModel);
719     }
720     
721     private PackageExplorerLabelProvider createLabelProvider() {
722         return new PackageExplorerLabelProvider(fContentProvider);
723     }
724     
725     private IElementComparer createElementComparer() {
726         if (showProjects())
727             return null;
728         else
729             return WorkingSetModel.COMPARER;
730     }
731     
732     private void fillActionBars() {
733         IActionBars actionBars= getViewSite().getActionBars();
734         fActionSet.fillActionBars(actionBars);
735     }
736     
737     private Object JavaDoc findInputElement() {
738         if (showWorkingSets()) {
739             return fWorkingSetModel;
740         } else {
741             Object JavaDoc input= getSite().getPage().getInput();
742             if (input instanceof IWorkspace) {
743                 return JavaCore.create(((IWorkspace)input).getRoot());
744             } else if (input instanceof IContainer) {
745                 IJavaElement element= JavaCore.create((IContainer)input);
746                 if (element != null && element.exists())
747                     return element;
748                 return input;
749             }
750             //1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
751
// we can't handle the input
752
// fall back to show the workspace
753
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
754         }
755     }
756     
757     /* (non-Javadoc)
758      * @see org.eclipse.ui.part.WorkbenchPart#getAdapter(java.lang.Class)
759      */

760     public Object JavaDoc getAdapter(Class JavaDoc key) {
761         if (key.equals(ISelectionProvider.class))
762             return fViewer;
763         if (key == IShowInSource.class) {
764             return getShowInSource();
765         }
766         if (key == IShowInTargetList.class) {
767             return new IShowInTargetList() {
768                 public String JavaDoc[] getShowInTargetIds() {
769                     return new String JavaDoc[] { IPageLayout.ID_RES_NAV };
770                 }
771
772             };
773         }
774         if (key == IContextProvider.class) {
775             return JavaUIHelp.getHelpContextProvider(this, IJavaHelpContextIds.PACKAGES_VIEW);
776         }
777         return super.getAdapter(key);
778     }
779
780     /**
781      * Returns the tool tip text for the given element.
782      * @param element the element
783      * @return the tooltip
784      */

785     String JavaDoc getToolTipText(Object JavaDoc element) {
786         String JavaDoc result;
787         if (!(element instanceof IResource)) {
788             if (element instanceof IJavaModel) {
789                 result= PackagesMessages.PackageExplorerPart_workspace;
790             } else if (element instanceof IJavaElement){
791                 result= JavaElementLabels.getTextLabel(element, JavaElementLabels.ALL_FULLY_QUALIFIED);
792             } else if (element instanceof IWorkingSet) {
793                 result= ((IWorkingSet)element).getLabel();
794             } else if (element instanceof WorkingSetModel) {
795                 result= PackagesMessages.PackageExplorerPart_workingSetModel;
796             } else {
797                 result= fLabelProvider.getText(element);
798             }
799         } else {
800             IPath path= ((IResource) element).getFullPath();
801             if (path.isRoot()) {
802                 result= PackagesMessages.PackageExplorer_title;
803             } else {
804                 result= path.makeRelative().toString();
805             }
806         }
807
808         if (fRootMode == ViewActionGroup.SHOW_PROJECTS) {
809             if (fWorkingSetLabel == null)
810                 return result;
811             if (result.length() == 0)
812                 return Messages.format(PackagesMessages.PackageExplorer_toolTip, new String JavaDoc[] { fWorkingSetLabel });
813             return Messages.format(PackagesMessages.PackageExplorer_toolTip2, new String JavaDoc[] { result, fWorkingSetLabel });
814         } else { // Working set mode. During initialization element and action set can be null.
815
if (element != null && !(element instanceof IWorkingSet) && !(element instanceof WorkingSetModel) && fActionSet != null) {
816                 FrameList frameList= fActionSet.getFrameList();
817                 int index= frameList.getCurrentIndex();
818                 IWorkingSet ws= null;
819                 while(index >= 0) {
820                     Frame frame= frameList.getFrame(index);
821                     if (frame instanceof TreeFrame) {
822                         Object JavaDoc input= ((TreeFrame)frame).getInput();
823                         if (input instanceof IWorkingSet) {
824                             ws= (IWorkingSet) input;
825                             break;
826                         }
827                     }
828                     index--;
829                 }
830                 if (ws != null) {
831                     return Messages.format(PackagesMessages.PackageExplorer_toolTip3, new String JavaDoc[] {ws.getLabel() , result});
832                 } else {
833                     return result;
834                 }
835             } else {
836                 return result;
837             }
838         }
839     }
840     
841     public String JavaDoc getTitleToolTip() {
842         if (fViewer == null)
843             return super.getTitleToolTip();
844         return getToolTipText(fViewer.getInput());
845     }
846     
847     /* (non-Javadoc)
848      * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
849      */

850     public void setFocus() {
851         fViewer.getTree().setFocus();
852     }
853
854     private ISelection getSelection() {
855         return fViewer.getSelection();
856     }
857       
858     //---- Action handling ----------------------------------------------------------
859

860     /* (non-Javadoc)
861      * @see IMenuListener#menuAboutToShow(IMenuManager)
862      */

863     public void menuAboutToShow(IMenuManager menu) {
864         JavaPlugin.createStandardGroups(menu);
865         
866         fActionSet.setContext(new ActionContext(getSelection()));
867         fActionSet.fillContextMenu(menu);
868         fActionSet.setContext(null);
869     }
870
871     private void makeActions() {
872
873         final PerformanceStats stats= PerformanceStats.getStats(PERF_MAKE_ACTIONS, this);
874         stats.startRun();
875
876         fActionSet= new PackageExplorerActionGroup(this);
877         if (fWorkingSetModel != null)
878             fActionSet.getWorkingSetActionGroup().setWorkingSetModel(fWorkingSetModel);
879
880         stats.endRun();
881     }
882     
883     // ---- Event handling ----------------------------------------------------------
884

885     private void initDragAndDrop() {
886         initDrag();
887         initDrop();
888     }
889
890     private void initDrag() {
891         int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
892         Transfer[] transfers= new Transfer[] {
893             LocalSelectionTransfer.getInstance(),
894             ResourceTransfer.getInstance(),
895             FileTransfer.getInstance()};
896         TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
897             new SelectionTransferDragAdapter(fViewer),
898             new ResourceTransferDragAdapter(fViewer),
899             new FileTransferDragAdapter(fViewer)
900         };
901         fViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fViewer, dragListeners));
902     }
903
904     private void initDrop() {
905         int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT;
906         Transfer[] transfers= new Transfer[] {
907             LocalSelectionTransfer.getInstance(),
908             FileTransfer.getInstance()};
909         TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
910             new SelectionTransferDropAdapter(fViewer),
911             new FileTransferDropAdapter(fViewer),
912             new WorkingSetDropAdapter(this)
913         };
914         fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
915     }
916
917     /**
918      * Handles post selection changed in viewer.
919      *
920      * Links to editor (if option enabled).
921      * @param event the selection eveny
922      */

923     private void handlePostSelectionChanged(SelectionChangedEvent event) {
924         ISelection selection= event.getSelection();
925         // If the selection is the same as the one that triggered the last
926
// open event then do nothing. The editor already got revealed.
927
if (isLinkingEnabled() && !selection.equals(fLastOpenSelection)) {
928             linkToEditor((IStructuredSelection)selection);
929         }
930         fLastOpenSelection= null;
931     }
932     
933     /* (non-Javadoc)
934      * @see org.eclipse.ui.part.ISetSelectionTarget#selectReveal(org.eclipse.jface.viewers.ISelection)
935      */

936     public void selectReveal(final ISelection selection) {
937         Control ctrl= getTreeViewer().getControl();
938         if (ctrl == null || ctrl.isDisposed())
939             return;
940         
941         fContentProvider.runPendingUpdates();
942         fViewer.setSelection(convertSelection(selection), true);
943     }
944
945     public ISelection convertSelection(ISelection s) {
946         if (!(s instanceof IStructuredSelection))
947             return s;
948             
949         Object JavaDoc[] elements= ((IStructuredSelection)s).toArray();
950         
951         boolean changed= false;
952         for (int i= 0; i < elements.length; i++) {
953             Object JavaDoc convertedElement= convertElement(elements[i]);
954             changed= changed || convertedElement != elements[i];
955             elements[i]= convertedElement;
956         }
957         if (changed)
958             return new StructuredSelection(elements);
959         else
960             return s;
961     }
962
963     private Object JavaDoc convertElement(Object JavaDoc original) {
964         if (original instanceof IJavaElement) {
965             if (original instanceof ICompilationUnit) {
966                 ICompilationUnit cu= (ICompilationUnit) original;
967                 IJavaProject javaProject= cu.getJavaProject();
968                 if (javaProject != null && javaProject.exists() && ! javaProject.isOnClasspath(cu)) {
969                     // could be a working copy of a .java file that is not on classpath
970
IResource resource= cu.getResource();
971                     if (resource != null)
972                         return resource;
973                 }
974                 
975             }
976             return original;
977         
978         } else if (original instanceof IResource) {
979             IJavaElement je= JavaCore.create((IResource)original);
980             if (je != null && je.exists()) {
981                 IJavaProject javaProject= je.getJavaProject();
982                 if (javaProject != null && javaProject.exists()) {
983                     return je;
984                 }
985             }
986         } else if (original instanceof IAdaptable) {
987             IAdaptable adaptable= (IAdaptable)original;
988             IJavaElement je= (IJavaElement) adaptable.getAdapter(IJavaElement.class);
989             if (je != null && je.exists())
990                 return je;
991             
992             IResource r= (IResource) adaptable.getAdapter(IResource.class);
993             if (r != null) {
994                 je= JavaCore.create(r);
995                 if (je != null && je.exists())
996                     return je;
997                 else
998                     return r;
999             }
1000        }
1001        return original;
1002    }
1003    
1004    public void selectAndReveal(Object JavaDoc element) {
1005        selectReveal(new StructuredSelection(element));
1006    }
1007    
1008    public boolean isLinkingEnabled() {
1009        return fLinkingEnabled;
1010    }
1011    
1012    /**
1013     * Links to editor (if option enabled)
1014     * @param selection the selection
1015     */

1016    private void linkToEditor(IStructuredSelection selection) {
1017        // ignore selection changes if the package explorer is not the active part.
1018
// In this case the selection change isn't triggered by a user.
1019
if (!isActivePart())
1020            return;
1021        Object JavaDoc obj= selection.getFirstElement();
1022
1023        if (selection.size() == 1) {
1024            IEditorPart part= EditorUtility.isOpenInEditor(obj);
1025            if (part != null) {
1026                IWorkbenchPage page= getSite().getPage();
1027                page.bringToTop(part);
1028                if (obj instanceof IJavaElement)
1029                    EditorUtility.revealInEditor(part, (IJavaElement)obj);
1030            }
1031        }
1032    }
1033
1034    private boolean isActivePart() {
1035        return this == getSite().getPage().getActivePart();
1036    }
1037    
1038    public void saveState(IMemento memento) {
1039        if (fViewer == null && fMemento != null) {
1040            // part has not been created -> keep the old state
1041
memento.putMemento(fMemento);
1042            return;
1043        }
1044        
1045        memento.putInteger(TAG_ROOT_MODE, fRootMode);
1046        if (fWorkingSetModel != null)
1047            fWorkingSetModel.saveState(memento);
1048        
1049        saveLayoutState(memento);
1050        saveLinkingEnabled(memento);
1051        
1052        if (fActionSet != null) {
1053            fActionSet.saveFilterAndSorterState(memento);
1054        }
1055    }
1056
1057    private void saveLinkingEnabled(IMemento memento) {
1058        memento.putInteger(TAG_LINK_EDITOR, fLinkingEnabled ? 1 : 0);
1059    }
1060
1061    private void saveLayoutState(IMemento memento) {
1062        if (memento != null) {
1063            memento.putInteger(TAG_LAYOUT, getLayoutAsInt());
1064            memento.putInteger(TAG_GROUP_LIBRARIES, fShowLibrariesNode ? 1 : 0);
1065        }
1066    }
1067    
1068    private void saveDialogSettings() {
1069        fDialogSettings.put(TAG_GROUP_LIBRARIES, fShowLibrariesNode);
1070        fDialogSettings.put(TAG_LAYOUT, getLayoutAsInt());
1071        fDialogSettings.put(TAG_ROOT_MODE, fRootMode);
1072        fDialogSettings.put(TAG_LINK_EDITOR, fLinkingEnabled);
1073    }
1074
1075    private int getLayoutAsInt() {
1076        if (fIsCurrentLayoutFlat)
1077            return FLAT_LAYOUT;
1078        else
1079            return HIERARCHICAL_LAYOUT;
1080    }
1081
1082    private void restoreFilterAndSorter() {
1083        fViewer.addFilter(new OutputFolderFilter());
1084        setComparator();
1085        if (fMemento != null)
1086            fActionSet.restoreFilterAndSorterState(fMemento);
1087    }
1088
1089    private void restoreLinkingEnabled(IMemento memento) {
1090        Integer JavaDoc val= memento.getInteger(TAG_LINK_EDITOR);
1091        fLinkingEnabled= val != null && val.intValue() != 0;
1092    }
1093    
1094    /**
1095     * Create the KeyListener for doing the refresh on the viewer.
1096     */

1097    private void initKeyListener() {
1098        fViewer.getControl().addKeyListener(new KeyAdapter() {
1099            public void keyReleased(KeyEvent event) {
1100                fActionSet.handleKeyEvent(event);
1101            }
1102        });
1103    }
1104
1105    /**
1106     * An editor has been activated. Set the selection in this Packages Viewer
1107     * to be the editor's input, if linking is enabled.
1108     * @param editor the activated editor
1109     */

1110    void editorActivated(IEditorPart editor) {
1111        IEditorInput editorInput= editor.getEditorInput();
1112        if (editorInput == null)
1113            return;
1114        Object JavaDoc input= getInputFromEditor(editorInput);
1115        if (input == null)
1116            return;
1117        if (!inputIsSelected(editorInput))
1118            showInput(input);
1119        else
1120            getTreeViewer().getTree().showSelection();
1121    }
1122    
1123    private Object JavaDoc getInputFromEditor(IEditorInput editorInput) {
1124        Object JavaDoc input= JavaUI.getEditorInputJavaElement(editorInput);
1125        if (input == null) {
1126            input= editorInput.getAdapter(IFile.class);
1127        }
1128        if (input == null && editorInput instanceof IStorageEditorInput) {
1129            try {
1130                input= ((IStorageEditorInput) editorInput).getStorage();
1131            } catch (CoreException e) {
1132                // ignore
1133
}
1134        }
1135        return input;
1136    }
1137    
1138
1139    private boolean inputIsSelected(IEditorInput input) {
1140        IStructuredSelection selection= (IStructuredSelection)fViewer.getSelection();
1141        if (selection.size() != 1)
1142            return false;
1143        IEditorInput selectionAsInput= null;
1144        try {
1145            selectionAsInput= EditorUtility.getEditorInput(selection.getFirstElement());
1146        } catch (JavaModelException e1) {
1147            return false;
1148        }
1149        return input.equals(selectionAsInput);
1150    }
1151
1152    boolean showInput(Object JavaDoc input) {
1153        Object JavaDoc element= null;
1154            
1155        if (input instanceof IFile && isOnClassPath((IFile)input)) {
1156            element= JavaCore.create((IFile)input);
1157        }
1158                
1159        if (element == null) // try a non Java resource
1160
element= input;
1161                
1162        if (element != null) {
1163            ISelection newSelection= new StructuredSelection(element);
1164            if (fViewer.getSelection().equals(newSelection)) {
1165                fViewer.reveal(element);
1166            } else {
1167                try {
1168                    fViewer.removePostSelectionChangedListener(fPostSelectionListener);
1169                    fViewer.setSelection(newSelection, true);
1170    
1171                    while (element != null && fViewer.getSelection().isEmpty()) {
1172                        // Try to select parent in case element is filtered
1173
element= getParent(element);
1174                        if (element != null) {
1175                            newSelection= new StructuredSelection(element);
1176                            fViewer.setSelection(newSelection, true);
1177                        }
1178                    }
1179                } finally {
1180                    fViewer.addPostSelectionChangedListener(fPostSelectionListener);
1181                }
1182            }
1183            return true;
1184        }
1185        return false;
1186    }
1187    
1188    private boolean isOnClassPath(IFile file) {
1189        IJavaProject jproject= JavaCore.create(file.getProject());
1190        return jproject.isOnClasspath(file);
1191    }
1192
1193    /**
1194     * Returns the element's parent.
1195     * @param element the element
1196     *
1197     * @return the parent or <code>null</code> if there's no parent
1198     */

1199    private Object JavaDoc getParent(Object JavaDoc element) {
1200        if (element instanceof IJavaElement)
1201            return ((IJavaElement)element).getParent();
1202        else if (element instanceof IResource)
1203            return ((IResource)element).getParent();
1204        else if (element instanceof IJarEntryResource) {
1205            return ((IJarEntryResource)element).getParent();
1206        }
1207        return null;
1208    }
1209    
1210    /**
1211     * A compilation unit or class was expanded, expand
1212     * the main type.
1213     * @param element the element
1214     */

1215    void expandMainType(Object JavaDoc element) {
1216        try {
1217            IType type= null;
1218            if (element instanceof ICompilationUnit) {
1219                ICompilationUnit cu= (ICompilationUnit)element;
1220                IType[] types= cu.getTypes();
1221                if (types.length > 0)
1222                    type= types[0];
1223            }
1224            else if (element instanceof IClassFile) {
1225                IClassFile cf= (IClassFile)element;
1226                type= cf.getType();
1227            }
1228            if (type != null) {
1229                final IType type2= type;
1230                Control ctrl= fViewer.getControl();
1231                if (ctrl != null && !ctrl.isDisposed()) {
1232                    ctrl.getDisplay().asyncExec(new Runnable JavaDoc() {
1233                        public void run() {
1234                            Control ctrl2= fViewer.getControl();
1235                            if (ctrl2 != null && !ctrl2.isDisposed())
1236                                fViewer.expandToLevel(type2, 1);
1237                        }
1238                    });
1239                }
1240            }
1241        } catch(JavaModelException e) {
1242            // no reveal
1243
}
1244    }
1245    
1246    /**
1247     * Returns the TreeViewer.
1248     * @return the tree viewer
1249     */

1250    public TreeViewer getTreeViewer() {
1251        return fViewer;
1252    }
1253    
1254    boolean isExpandable(Object JavaDoc element) {
1255        if (fViewer == null)
1256            return false;
1257        return fViewer.isExpandable(element);
1258    }
1259
1260    void setWorkingSetLabel(String JavaDoc workingSetName) {
1261        fWorkingSetLabel= workingSetName;
1262        setTitleToolTip(getTitleToolTip());
1263    }
1264    
1265    /**
1266     * Updates the title text and title tool tip.
1267     * Called whenever the input of the viewer changes.
1268     */

1269    void updateTitle() {
1270        Object JavaDoc input= fViewer.getInput();
1271        if (input == null
1272            || (input instanceof IJavaModel)) {
1273            setContentDescription(""); //$NON-NLS-1$
1274
setTitleToolTip(""); //$NON-NLS-1$
1275
} else {
1276            String JavaDoc inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
1277            setContentDescription(inputText);
1278            setTitleToolTip(getToolTipText(input));
1279        }
1280    }
1281    
1282    /**
1283     * Sets the decorator for the package explorer.
1284     *
1285     * @param decorator a label decorator or <code>null</code> for no decorations.
1286     * @deprecated To be removed
1287     */

1288    public void setLabelDecorator(ILabelDecorator decorator) {
1289    }
1290    
1291    /*
1292     * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1293     */

1294    public void propertyChange(PropertyChangeEvent event) {
1295        if (fViewer == null)
1296            return;
1297        
1298        boolean refreshViewer= false;
1299    
1300        if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) {
1301            fActionSet.updateActionBars(getViewSite().getActionBars());
1302            
1303            boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
1304            ((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
1305            
1306            refreshViewer= true;
1307        } else if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) {
1308            refreshViewer= true;
1309        }
1310
1311        if (refreshViewer)
1312            fViewer.refresh();
1313    }
1314    
1315    /* (non-Javadoc)
1316     * @see IViewPartInputProvider#getViewPartInput()
1317     */

1318    public Object JavaDoc getViewPartInput() {
1319        if (fViewer != null) {
1320            return fViewer.getInput();
1321        }
1322        return null;
1323    }
1324
1325    public void collapseAll() {
1326        try {
1327            fViewer.getControl().setRedraw(false);
1328            fViewer.collapseToLevel(getViewPartInput(), AbstractTreeViewer.ALL_LEVELS);
1329        } finally {
1330            fViewer.getControl().setRedraw(true);
1331        }
1332    }
1333    
1334    /* (non-Javadoc)
1335     * @see org.eclipse.ui.part.IShowInTarget#show(org.eclipse.ui.part.ShowInContext)
1336     */

1337    public boolean show(ShowInContext context) {
1338        ISelection selection= context.getSelection();
1339        if (selection instanceof IStructuredSelection) {
1340            // fix for 64634 Navigate/Show in/Package Explorer doesn't work
1341
IStructuredSelection structuredSelection= ((IStructuredSelection) selection);
1342            if (structuredSelection.size() == 1) {
1343                int res= tryToReveal(structuredSelection.getFirstElement());
1344                if (res == IStatus.OK)
1345                    return true;
1346                if (res == IStatus.CANCEL)
1347                    return false;
1348            } else if (structuredSelection.size() > 1) {
1349                selectReveal(structuredSelection);
1350                return true;
1351            }
1352        }
1353        
1354        Object JavaDoc input= context.getInput();
1355        if (input instanceof IEditorInput) {
1356            Object JavaDoc elementOfInput= getInputFromEditor((IEditorInput) input);
1357            return elementOfInput != null && (tryToReveal(elementOfInput) == IStatus.OK);
1358        }
1359
1360        return false;
1361    }
1362
1363    /**
1364     * Returns the <code>IShowInSource</code> for this view.
1365     * @return the <code>IShowInSource</code>
1366     */

1367    protected IShowInSource getShowInSource() {
1368        return new IShowInSource() {
1369            public ShowInContext getShowInContext() {
1370                return new ShowInContext(
1371                    getTreeViewer().getInput(),
1372                    getTreeViewer().getSelection());
1373            }
1374        };
1375    }
1376
1377    /* (non-Javadoc)
1378     * @see org.eclipse.jdt.ui.IPackagesViewPart#setLinkingEnabled(boolean)
1379     */

1380    public void setLinkingEnabled(boolean enabled) {
1381        fLinkingEnabled= enabled;
1382        saveDialogSettings();
1383        
1384        IWorkbenchPage page= getSite().getPage();
1385        if (enabled) {
1386            page.addPartListener(fLinkWithEditorListener);
1387            
1388            IEditorPart editor = page.getActiveEditor();
1389            if (editor != null) {
1390                editorActivated(editor);
1391            }
1392        } else {
1393            page.removePartListener(fLinkWithEditorListener);
1394        }
1395    }
1396
1397    /**
1398     * Returns the name for the given element.
1399     * Used as the name for the current frame.
1400     * @param element the elemeny
1401     * @return the name of the frame
1402     */

1403    String JavaDoc getFrameName(Object JavaDoc element) {
1404        if (element instanceof IJavaElement) {
1405            return ((IJavaElement) element).getElementName();
1406        } else if (element instanceof WorkingSetModel) {
1407            return ""; //$NON-NLS-1$
1408
} else {
1409            return fLabelProvider.getText(element);
1410        }
1411    }
1412    
1413    public int tryToReveal(Object JavaDoc element) {
1414        if (revealElementOrParent(element))
1415            return IStatus.OK;
1416        
1417        WorkingSetFilterActionGroup workingSetGroup= fActionSet.getWorkingSetActionGroup().getFilterGroup();
1418        if (workingSetGroup != null) {
1419            IWorkingSet workingSet= workingSetGroup.getWorkingSet();
1420            if (workingSetGroup.isFiltered(getVisibleParent(element), element)) {
1421                String JavaDoc message;
1422                if (element instanceof IJavaElement) {
1423                    String JavaDoc elementLabel= JavaElementLabels.getElementLabel((IJavaElement)element, JavaElementLabels.ALL_DEFAULT);
1424                    message= Messages.format(PackagesMessages.PackageExplorerPart_notFoundSepcific, new String JavaDoc[] {elementLabel, workingSet.getLabel()});
1425                } else {
1426                    message= Messages.format(PackagesMessages.PackageExplorer_notFound, workingSet.getLabel());
1427                }
1428                if (MessageDialog.openQuestion(getSite().getShell(), PackagesMessages.PackageExplorer_filteredDialog_title, message)) {
1429                    workingSetGroup.setWorkingSet(null, true);
1430                    if (revealElementOrParent(element))
1431                        return IStatus.OK;
1432                } else {
1433                    return IStatus.CANCEL;
1434                }
1435            }
1436        }
1437        // try to remove filters
1438
CustomFiltersActionGroup filterGroup= fActionSet.getCustomFilterActionGroup();
1439        String JavaDoc[] currentFilters= filterGroup.internalGetEnabledFilterIds();
1440        String JavaDoc[] newFilters= filterGroup.removeFiltersFor(getVisibleParent(element), element, getTreeViewer().getContentProvider());
1441        if (currentFilters.length > newFilters.length) {
1442            String JavaDoc message;
1443            if (element instanceof IJavaElement) {
1444                String JavaDoc elementLabel= JavaElementLabels.getElementLabel((IJavaElement)element, JavaElementLabels.ALL_DEFAULT);
1445                message= Messages.format(PackagesMessages.PackageExplorerPart_removeFiltersSpecific, elementLabel);
1446            } else {
1447                message= PackagesMessages.PackageExplorer_removeFilters;
1448            }
1449            if (MessageDialog.openQuestion(getSite().getShell(), PackagesMessages.PackageExplorer_filteredDialog_title, message)) {
1450                filterGroup.setFilters(newFilters);
1451                if (revealElementOrParent(element))
1452                    return IStatus.OK;
1453            } else {
1454                return IStatus.CANCEL;
1455            }
1456        }
1457        FrameAction action= fActionSet.getUpAction();
1458        while (action.getFrameList().getCurrentIndex() > 0) {
1459            // only try to go up if there is a parent frame
1460
// fix for bug# 63769 Endless loop after Show in Package Explorer
1461
if (action.getFrameList().getSource().getFrame(IFrameSource.PARENT_FRAME, 0) == null)
1462                break;
1463            action.run();
1464            if (revealElementOrParent(element))
1465                return IStatus.OK;
1466        }
1467        return IStatus.ERROR;
1468    }
1469    
1470    private boolean revealElementOrParent(Object JavaDoc element) {
1471        if (revealAndVerify(element))
1472            return true;
1473        element= getVisibleParent(element);
1474        if (element != null) {
1475            if (revealAndVerify(element))
1476                return true;
1477            if (element instanceof IJavaElement) {
1478                IResource resource= ((IJavaElement)element).getResource();
1479                if (resource != null) {
1480                    if (revealAndVerify(resource))
1481                        return true;
1482                }
1483            }
1484        }
1485        return false;
1486    }
1487
1488    private Object JavaDoc getVisibleParent(Object JavaDoc object) {
1489        // Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19104
1490
if (object == null)
1491            return null;
1492        if (!(object instanceof IJavaElement))
1493            return object;
1494        IJavaElement element2= (IJavaElement) object;
1495        switch (element2.getElementType()) {
1496            case IJavaElement.IMPORT_DECLARATION:
1497            case IJavaElement.PACKAGE_DECLARATION:
1498            case IJavaElement.IMPORT_CONTAINER:
1499            case IJavaElement.TYPE:
1500            case IJavaElement.METHOD:
1501            case IJavaElement.FIELD:
1502            case IJavaElement.INITIALIZER:
1503                // select parent cu/classfile
1504
element2= (IJavaElement)element2.getOpenable();
1505                break;
1506            case IJavaElement.JAVA_MODEL:
1507                element2= null;
1508                break;
1509        }
1510        return element2;
1511    }
1512
1513    private boolean revealAndVerify(Object JavaDoc element) {
1514        if (element == null)
1515            return false;
1516        selectReveal(new StructuredSelection(element));
1517        return ! getSite().getSelectionProvider().getSelection().isEmpty();
1518    }
1519
1520    public void rootModeChanged(int newMode) {
1521        fRootMode= newMode;
1522        saveDialogSettings();
1523        
1524        if (showWorkingSets() && fWorkingSetModel == null) {
1525            createWorkingSetModel();
1526            if (fActionSet != null) {
1527                fActionSet.getWorkingSetActionGroup().setWorkingSetModel(fWorkingSetModel);
1528            }
1529        }
1530        IStructuredSelection selection= new StructuredSelection(((IStructuredSelection) fViewer.getSelection()).toArray());
1531        Object JavaDoc input= fViewer.getInput();
1532        boolean isRootInputChange= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).equals(input)
1533            || (fWorkingSetModel != null && fWorkingSetModel.equals(input))
1534            || input instanceof IWorkingSet;
1535        try {
1536            fViewer.getControl().setRedraw(false);
1537            if (isRootInputChange) {
1538                fViewer.setInput(null);
1539            }
1540            setProviders();
1541            setComparator();
1542            fActionSet.getWorkingSetActionGroup().fillFilters(fViewer);
1543            if (isRootInputChange) {
1544                fViewer.setInput(findInputElement());
1545            }
1546            fViewer.setSelection(selection, true);
1547        } finally {
1548            fViewer.getControl().setRedraw(true);
1549        }
1550        if (isRootInputChange && showWorkingSets() && fWorkingSetModel.needsConfiguration()) {
1551            ConfigureWorkingSetAction action= new ConfigureWorkingSetAction(getSite());
1552            action.setWorkingSetModel(fWorkingSetModel);
1553            action.run();
1554            fWorkingSetModel.configured();
1555        }
1556        setTitleToolTip(getTitleToolTip());
1557    }
1558
1559    private void createWorkingSetModel() {
1560        SafeRunner.run(new ISafeRunnable() {
1561            public void run() throws Exception JavaDoc {
1562                fWorkingSetModel= new WorkingSetModel(fMemento);
1563            }
1564            public void handleException(Throwable JavaDoc exception) {
1565                fWorkingSetModel= new WorkingSetModel(null);
1566            }
1567        });
1568    }
1569    
1570
1571    /**
1572     * @return the selected working set to filter if in root mode {@link ViewActionGroup#SHOW_PROJECTS}
1573     */

1574    public IWorkingSet getFilterWorkingSet() {
1575        if (!showProjects())
1576            return null;
1577        
1578        if (fActionSet == null)
1579            return null;
1580        
1581        return fActionSet.getWorkingSetActionGroup().getFilterGroup().getWorkingSet();
1582    }
1583
1584    public WorkingSetModel getWorkingSetModel() {
1585        return fWorkingSetModel;
1586    }
1587    
1588    public int getRootMode() {
1589        return fRootMode;
1590    }
1591    
1592    /* package */ boolean showProjects() {
1593        return fRootMode == ViewActionGroup.SHOW_PROJECTS;
1594    }
1595    
1596    /* package */ boolean showWorkingSets() {
1597        return fRootMode == ViewActionGroup.SHOW_WORKING_SETS;
1598    }
1599    
1600    private void setComparator() {
1601        if (showWorkingSets()) {
1602            fViewer.setComparator(new WorkingSetAwareJavaElementSorter());
1603        } else {
1604            fViewer.setComparator(new JavaElementComparator());
1605        }
1606    }
1607    
1608    //---- test methods for working set mode -------------------------------
1609

1610    public void internalTestShowWorkingSets(IWorkingSet[] workingSets) {
1611        if (fWorkingSetModel == null)
1612            createWorkingSetModel();
1613        fWorkingSetModel.setActiveWorkingSets(workingSets);
1614        fWorkingSetModel.configured();
1615        rootModeChanged(ViewActionGroup.SHOW_WORKING_SETS);
1616    }
1617}
1618
Popular Tags