KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > views > navigator > ResourceNavigator


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 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  * Benjamin Muskalla - bug 105041
11  *******************************************************************************/

12
13 package org.eclipse.ui.views.navigator;
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.Arrays JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.List JavaDoc;
19
20 import org.eclipse.core.resources.IContainer;
21 import org.eclipse.core.resources.IFile;
22 import org.eclipse.core.resources.IMarker;
23 import org.eclipse.core.resources.IResource;
24 import org.eclipse.core.resources.IWorkspace;
25 import org.eclipse.core.resources.ResourcesPlugin;
26 import org.eclipse.core.runtime.IAdaptable;
27 import org.eclipse.core.runtime.IPath;
28 import org.eclipse.jface.action.IMenuListener;
29 import org.eclipse.jface.action.IMenuManager;
30 import org.eclipse.jface.action.MenuManager;
31 import org.eclipse.jface.dialogs.IDialogSettings;
32 import org.eclipse.jface.preference.IPreferenceStore;
33 import org.eclipse.jface.util.IPropertyChangeListener;
34 import org.eclipse.jface.util.PropertyChangeEvent;
35 import org.eclipse.jface.viewers.DecoratingLabelProvider;
36 import org.eclipse.jface.viewers.DoubleClickEvent;
37 import org.eclipse.jface.viewers.IDoubleClickListener;
38 import org.eclipse.jface.viewers.ILabelDecorator;
39 import org.eclipse.jface.viewers.ILabelProvider;
40 import org.eclipse.jface.viewers.IOpenListener;
41 import org.eclipse.jface.viewers.ISelection;
42 import org.eclipse.jface.viewers.ISelectionChangedListener;
43 import org.eclipse.jface.viewers.IStructuredSelection;
44 import org.eclipse.jface.viewers.OpenEvent;
45 import org.eclipse.jface.viewers.SelectionChangedEvent;
46 import org.eclipse.jface.viewers.StructuredSelection;
47 import org.eclipse.jface.viewers.TreeViewer;
48 import org.eclipse.jface.viewers.ViewerComparator;
49 import org.eclipse.jface.viewers.ViewerSorter;
50 import org.eclipse.osgi.util.NLS;
51 import org.eclipse.swt.SWT;
52 import org.eclipse.swt.dnd.DND;
53 import org.eclipse.swt.dnd.FileTransfer;
54 import org.eclipse.swt.dnd.Transfer;
55 import org.eclipse.swt.events.KeyEvent;
56 import org.eclipse.swt.events.KeyListener;
57 import org.eclipse.swt.widgets.Composite;
58 import org.eclipse.swt.widgets.Control;
59 import org.eclipse.swt.widgets.Event;
60 import org.eclipse.swt.widgets.Listener;
61 import org.eclipse.swt.widgets.Menu;
62 import org.eclipse.swt.widgets.Shell;
63 import org.eclipse.ui.IEditorPart;
64 import org.eclipse.ui.IMemento;
65 import org.eclipse.ui.IPartListener;
66 import org.eclipse.ui.IViewSite;
67 import org.eclipse.ui.IWorkbenchPage;
68 import org.eclipse.ui.IWorkbenchPart;
69 import org.eclipse.ui.IWorkbenchPreferenceConstants;
70 import org.eclipse.ui.IWorkingSet;
71 import org.eclipse.ui.IWorkingSetManager;
72 import org.eclipse.ui.PartInitException;
73 import org.eclipse.ui.PlatformUI;
74 import org.eclipse.ui.ResourceWorkingSetFilter;
75 import org.eclipse.ui.actions.ActionContext;
76 import org.eclipse.ui.actions.OpenResourceAction;
77 import org.eclipse.ui.ide.ResourceUtil;
78 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
79 import org.eclipse.ui.internal.views.navigator.ResourceNavigatorMessages;
80 import org.eclipse.ui.model.WorkbenchContentProvider;
81 import org.eclipse.ui.model.WorkbenchLabelProvider;
82 import org.eclipse.ui.part.ISetSelectionTarget;
83 import org.eclipse.ui.part.IShowInSource;
84 import org.eclipse.ui.part.IShowInTarget;
85 import org.eclipse.ui.part.PluginTransfer;
86 import org.eclipse.ui.part.ResourceTransfer;
87 import org.eclipse.ui.part.ShowInContext;
88 import org.eclipse.ui.part.ViewPart;
89 import org.eclipse.ui.plugin.AbstractUIPlugin;
90 import org.eclipse.ui.views.framelist.FrameList;
91 import org.eclipse.ui.views.framelist.TreeFrame;
92
93 /**
94  * Implements the Resource Navigator view.
95  */

96 public class ResourceNavigator extends ViewPart implements ISetSelectionTarget,
97         IResourceNavigator {
98
99     private TreeViewer viewer;
100
101     private IDialogSettings settings;
102
103     private IMemento memento;
104
105     private FrameList frameList;
106
107     private ResourceNavigatorActionGroup actionGroup;
108
109     private ResourcePatternFilter patternFilter = new ResourcePatternFilter();
110
111     private ResourceWorkingSetFilter workingSetFilter = new ResourceWorkingSetFilter();
112
113     private boolean linkingEnabled;
114
115     private boolean dragDetected;
116
117     private Listener dragDetectListener;
118     /**
119      * Remembered working set.
120      */

121     private IWorkingSet workingSet;
122
123     /**
124      * Marks whether the working set we're using is currently empty. In this
125      * event we're effectively not using a working set.
126      */

127     private boolean emptyWorkingSet = false;
128     
129     /**
130      * Settings constant for section name (value <code>ResourceNavigator</code>).
131      */

132     private static final String JavaDoc STORE_SECTION = "ResourceNavigator"; //$NON-NLS-1$
133

134     /**
135      * Settings constant for sort order (value <code>ResourceViewer.STORE_SORT_TYPE</code>).
136      */

137     private static final String JavaDoc STORE_SORT_TYPE = "ResourceViewer.STORE_SORT_TYPE"; //$NON-NLS-1$
138

139     /**
140      * Settings constant for working set (value <code>ResourceWorkingSetFilter.STORE_WORKING_SET</code>).
141      */

142     private static final String JavaDoc STORE_WORKING_SET = "ResourceWorkingSetFilter.STORE_WORKING_SET"; //$NON-NLS-1$
143

144     /**
145      * @deprecated No longer used but preserved to avoid an api change.
146      */

147     public static final String JavaDoc NAVIGATOR_VIEW_HELP_ID = INavigatorHelpContextIds.RESOURCE_VIEW;
148
149     /**
150      * True iff we've already scheduled an asynchronous call to linkToEditor
151      */

152     private boolean linkScheduled = false;
153     
154     // Persistance tags.
155
private static final String JavaDoc TAG_SORTER = "sorter"; //$NON-NLS-1$
156

157     private static final String JavaDoc TAG_FILTERS = "filters"; //$NON-NLS-1$
158

159     private static final String JavaDoc TAG_FILTER = "filter"; //$NON-NLS-1$
160

161     private static final String JavaDoc TAG_SELECTION = "selection"; //$NON-NLS-1$
162

163     private static final String JavaDoc TAG_EXPANDED = "expanded"; //$NON-NLS-1$
164

165     private static final String JavaDoc TAG_ELEMENT = "element"; //$NON-NLS-1$
166

167     private static final String JavaDoc TAG_IS_ENABLED = "isEnabled"; //$NON-NLS-1$
168

169     private static final String JavaDoc TAG_PATH = "path"; //$NON-NLS-1$
170

171     private static final String JavaDoc TAG_CURRENT_FRAME = "currentFrame"; //$NON-NLS-1$
172

173     private IPartListener partListener = new IPartListener() {
174         public void partActivated(IWorkbenchPart part) {
175             if (part instanceof IEditorPart) {
176                 editorActivated((IEditorPart) part);
177             }
178         }
179
180         public void partBroughtToTop(IWorkbenchPart part) {
181         }
182
183         public void partClosed(IWorkbenchPart part) {
184         }
185
186         public void partDeactivated(IWorkbenchPart part) {
187         }
188
189         public void partOpened(IWorkbenchPart part) {
190         }
191     };
192
193     private IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener() {
194         public void propertyChange(PropertyChangeEvent event) {
195             String JavaDoc property = event.getProperty();
196             Object JavaDoc newValue = event.getNewValue();
197             Object JavaDoc oldValue = event.getOldValue();
198            
199             if (IWorkingSetManager.CHANGE_WORKING_SET_REMOVE.equals(property)
200                     && oldValue == workingSet) {
201                 setWorkingSet(null);
202             } else if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE
203                     .equals(property)
204                     && newValue == workingSet) {
205                 updateTitle();
206             } else if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE
207                     .equals(property)
208                     && newValue == workingSet) {
209                 if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) {
210                     // act as if the working set has been made null
211
if (!emptyWorkingSet) {
212                         emptyWorkingSet = true;
213                         workingSetFilter.setWorkingSet(null);
214                     }
215                 } else {
216                     // we've gone from empty to non-empty on our set.
217
// Restore it.
218
if (emptyWorkingSet) {
219                         emptyWorkingSet = false;
220                         workingSetFilter.setWorkingSet(workingSet);
221                     }
222                 }
223                 getViewer().refresh();
224             }
225         }
226     };
227
228     /**
229      * Constructs a new resource navigator view.
230      */

231     public ResourceNavigator() {
232         IDialogSettings viewsSettings = getPlugin().getDialogSettings();
233
234         settings = viewsSettings.getSection(STORE_SECTION);
235         if (settings == null) {
236             settings = viewsSettings.addNewSection(STORE_SECTION);
237         }
238
239         initLinkingEnabled();
240     }
241
242     /**
243      * Converts the given selection into a form usable by the viewer,
244      * where the elements are resources.
245      */

246     private StructuredSelection convertSelection(ISelection selection) {
247         ArrayList JavaDoc list = new ArrayList JavaDoc();
248         if (selection instanceof IStructuredSelection) {
249             IStructuredSelection ssel = (IStructuredSelection) selection;
250             for (Iterator JavaDoc i = ssel.iterator(); i.hasNext();) {
251                 Object JavaDoc o = i.next();
252                 IResource resource = null;
253                 if (o instanceof IResource) {
254                     resource = (IResource) o;
255                 } else {
256                     if (o instanceof IAdaptable) {
257                         resource = (IResource) ((IAdaptable) o)
258                                 .getAdapter(IResource.class);
259                     }
260                 }
261                 if (resource != null) {
262                     list.add(resource);
263                 }
264             }
265         }
266         return new StructuredSelection(list);
267     }
268
269     /* (non-Javadoc)
270      * Method declared on IWorkbenchPart.
271      */

272     public void createPartControl(Composite parent) {
273         TreeViewer viewer = createViewer(parent);
274         this.viewer = viewer;
275
276         if (memento != null) {
277             restoreFilters();
278             restoreLinkingEnabled();
279         }
280         frameList = createFrameList();
281         initDragAndDrop();
282         updateTitle();
283
284         initContextMenu();
285
286         initResourceComparator();
287         initWorkingSetFilter();
288
289         // make sure input is set after sorters and filters,
290
// to avoid unnecessary refreshes
291
viewer.setInput(getInitialInput());
292
293         // make actions after setting input, because some actions
294
// look at the viewer for enablement (e.g. the Up action)
295
makeActions();
296
297         // Fill the action bars and update the global action handlers'
298
// enabled state to match the current selection.
299
getActionGroup().fillActionBars(getViewSite().getActionBars());
300         updateActionBars((IStructuredSelection) viewer.getSelection());
301
302         getSite().setSelectionProvider(viewer);
303         getSite().getPage().addPartListener(partListener);
304         IWorkingSetManager workingSetManager = getPlugin().getWorkbench()
305                 .getWorkingSetManager();
306         workingSetManager.addPropertyChangeListener(propertyChangeListener);
307
308         if (memento != null) {
309             restoreState(memento);
310         }
311         memento = null;
312
313         // Set help for the view
314
getSite().getWorkbenchWindow().getWorkbench().getHelpSystem().setHelp(
315                 viewer.getControl(), getHelpContextId());
316     }
317
318     /**
319      * Returns the help context id to use for this view.
320      *
321      * @since 2.0
322      */

323     protected String JavaDoc getHelpContextId() {
324         return INavigatorHelpContextIds.RESOURCE_VIEW;
325     }
326
327     /**
328      * Initializes and registers the context menu.
329      *
330      * @since 2.0
331      */

332     protected void initContextMenu() {
333         MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
334
menuMgr.setRemoveAllWhenShown(true);
335         menuMgr.addMenuListener(new IMenuListener() {
336             public void menuAboutToShow(IMenuManager manager) {
337                 ResourceNavigator.this.fillContextMenu(manager);
338             }
339         });
340         TreeViewer viewer = getTreeViewer();
341         Menu menu = menuMgr.createContextMenu(viewer.getTree());
342         viewer.getTree().setMenu(menu);
343         getSite().registerContextMenu(menuMgr, viewer);
344     }
345
346     /**
347      * Creates the viewer.
348      *
349      * @param parent the parent composite
350      * @since 2.0
351      */

352     protected TreeViewer createViewer(Composite parent) {
353         TreeViewer viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL
354                 | SWT.V_SCROLL);
355         viewer.setUseHashlookup(true);
356         initContentProvider(viewer);
357         initLabelProvider(viewer);
358         initFilters(viewer);
359         initListeners(viewer);
360
361         return viewer;
362     }
363
364     /**
365      * Sets the content provider for the viewer.
366      *
367      * @param viewer the viewer
368      * @since 2.0
369      */

370     protected void initContentProvider(TreeViewer viewer) {
371         viewer.setContentProvider(new WorkbenchContentProvider());
372     }
373
374     /**
375      * Sets the label provider for the viewer.
376      *
377      * @param viewer the viewer
378      * @since 2.0
379      */

380     protected void initLabelProvider(TreeViewer viewer) {
381         viewer.setLabelProvider(new DecoratingLabelProvider(
382                 new WorkbenchLabelProvider(), getPlugin().getWorkbench()
383                         .getDecoratorManager().getLabelDecorator()));
384     }
385
386     /**
387      * Adds the filters to the viewer.
388      *
389      * @param viewer the viewer
390      * @since 2.0
391      */

392     protected void initFilters(TreeViewer viewer) {
393         viewer.addFilter(patternFilter);
394         viewer.addFilter(workingSetFilter);
395     }
396
397     /**
398      * Initializes the linking enabled setting from the preference store.
399      */

400     private void initLinkingEnabled() {
401         // Try the dialog settings first, which remember the last choice.
402
String JavaDoc setting = settings
403                 .get(IWorkbenchPreferenceConstants.LINK_NAVIGATOR_TO_EDITOR);
404         if (setting != null) {
405             linkingEnabled = setting.equals("true"); //$NON-NLS-1$
406
return;
407         }
408         // If not in the dialog settings, check the preference store for the default setting.
409
// Use the UI plugin's preference store since this is a public preference.
410
linkingEnabled = PlatformUI.getPreferenceStore().getBoolean(
411                 IWorkbenchPreferenceConstants.LINK_NAVIGATOR_TO_EDITOR);
412     }
413
414     /**
415      * Adds the listeners to the viewer.
416      *
417      * @param viewer the viewer
418      * @since 2.0
419      */

420     protected void initListeners(TreeViewer viewer) {
421         viewer.addSelectionChangedListener(new ISelectionChangedListener() {
422             public void selectionChanged(SelectionChangedEvent event) {
423                 handleSelectionChanged(event);
424             }
425         });
426         viewer.addDoubleClickListener(new IDoubleClickListener() {
427             public void doubleClick(DoubleClickEvent event) {
428                 handleDoubleClick(event);
429             }
430         });
431         viewer.addOpenListener(new IOpenListener() {
432             public void open(OpenEvent event) {
433                 handleOpen(event);
434             }
435         });
436         viewer.getControl().addKeyListener(new KeyListener() {
437             public void keyPressed(KeyEvent event) {
438                 handleKeyPressed(event);
439             }
440
441             public void keyReleased(KeyEvent event) {
442                 handleKeyReleased(event);
443             }
444         });
445     }
446
447     /* (non-Javadoc)
448      * Method declared on IWorkbenchPart.
449      */

450     public void dispose() {
451         getSite().getPage().removePartListener(partListener);
452
453         IWorkingSetManager workingSetManager = getPlugin().getWorkbench()
454                 .getWorkingSetManager();
455         workingSetManager.removePropertyChangeListener(propertyChangeListener);
456
457         if (getActionGroup() != null) {
458             getActionGroup().dispose();
459         }
460         Control control = viewer.getControl();
461         if (dragDetectListener != null && control != null
462                 && control.isDisposed() == false) {
463             control.removeListener(SWT.DragDetect, dragDetectListener);
464         }
465         super.dispose();
466     }
467
468     /**
469      * An editor has been activated. Sets the selection in this navigator
470      * to be the editor's input, if linking is enabled.
471      *
472      * @param editor the active editor
473      * @since 2.0
474      */

475     protected void editorActivated(IEditorPart editor) {
476         if (!isLinkingEnabled()) {
477             return;
478         }
479
480         IFile file = ResourceUtil.getFile(editor.getEditorInput());
481         if (file != null) {
482             ISelection newSelection = new StructuredSelection(file);
483             if (getTreeViewer().getSelection().equals(newSelection)) {
484                 getTreeViewer().getTree().showSelection();
485             } else {
486                 getTreeViewer().setSelection(newSelection, true);
487             }
488         }
489     }
490
491     /**
492      * Called when the context menu is about to open.
493      * Delegates to the action group using the viewer's selection as the action context.
494      * @since 2.0
495      */

496     protected void fillContextMenu(IMenuManager menu) {
497         IStructuredSelection selection = (IStructuredSelection) getViewer()
498                 .getSelection();
499         getActionGroup().setContext(new ActionContext(selection));
500         getActionGroup().fillContextMenu(menu);
501     }
502
503     /*
504      * @see IResourceNavigatorPart
505      * @since 2.0
506      */

507     public FrameList getFrameList() {
508         return frameList;
509     }
510
511     /**
512      * Returns the initial input for the viewer.
513      * Tries to convert the page input to a resource, either directly or via IAdaptable.
514      * If the resource is a container, it uses that.
515      * If the resource is a file, it uses its parent folder.
516      * If a resource could not be obtained, it uses the workspace root.
517      *
518      * @since 2.0
519      */

520     protected IAdaptable getInitialInput() {
521         IAdaptable input = getSite().getPage().getInput();
522         if (input != null) {
523             IResource resource = null;
524             if (input instanceof IResource) {
525                 resource = (IResource) input;
526             } else {
527                 resource = (IResource) input.getAdapter(IResource.class);
528             }
529             if (resource != null) {
530                 switch (resource.getType()) {
531                 case IResource.FILE:
532                     return resource.getParent();
533                 case IResource.FOLDER:
534                 case IResource.PROJECT:
535                 case IResource.ROOT:
536                     return resource;
537                 default:
538                     // Unknown resource type. Fall through.
539
break;
540                 }
541             }
542         }
543         return ResourcesPlugin.getWorkspace().getRoot();
544     }
545
546     /**
547      * Returns the pattern filter for this view.
548      *
549      * @return the pattern filter
550      * @since 2.0
551      */

552     public ResourcePatternFilter getPatternFilter() {
553         return this.patternFilter;
554     }
555
556     /**
557      * Returns the working set for this view.
558      *
559      * @return the working set
560      * @since 2.0
561      */

562     public IWorkingSet getWorkingSet() {
563         return workingSetFilter.getWorkingSet();
564     }
565
566     /**
567      * Returns the navigator's plugin.
568      * @return the UI plugin for this bundle
569      */

570     public AbstractUIPlugin getPlugin() {
571         return IDEWorkbenchPlugin.getDefault();
572     }
573
574     /**
575      * Return the sorter.
576      *
577      * @since 2.0
578      * @deprecated as of 3.3, use {@link ResourceNavigator#getComparator()}
579      */

580     public ResourceSorter getSorter() {
581         return (ResourceSorter) getTreeViewer().getSorter();
582     }
583
584     /**
585      * Returns the comparator.
586      *
587      * @return the <code>ResourceComparator</code>
588      * @since 3.3
589      */

590
591     public ResourceComparator getComparator(){
592         return (ResourceComparator) getTreeViewer().getComparator();
593     }
594     /**
595      * Returns the resource viewer which shows the resource hierarchy.
596      * @since 2.0
597      */

598     public TreeViewer getViewer() {
599         return viewer;
600     }
601
602     /**
603      * Returns the tree viewer which shows the resource hierarchy.
604      * @return the tree viewer
605      * @since 2.0
606      */

607     public TreeViewer getTreeViewer() {
608         return viewer;
609     }
610
611     /**
612      * Returns the shell to use for opening dialogs.
613      * Used in this class, and in the actions.
614      *
615      * @return the shell
616      * @deprecated use getViewSite().getShell()
617      */

618     public Shell getShell() {
619         return getViewSite().getShell();
620     }
621
622     /**
623      * Returns the message to show in the status line.
624      *
625      * @param selection the current selection
626      * @return the status line message
627      * @since 2.0
628      */

629     protected String JavaDoc getStatusLineMessage(IStructuredSelection selection) {
630         if (selection.size() == 1) {
631             Object JavaDoc o = selection.getFirstElement();
632             if (o instanceof IResource) {
633                 return ((IResource) o).getFullPath().makeRelative().toString();
634             }
635             return ResourceNavigatorMessages.ResourceNavigator_oneItemSelected;
636         }
637         if (selection.size() > 1) {
638             return NLS.bind(ResourceNavigatorMessages.ResourceNavigator_statusLine, String.valueOf(selection.size()));
639         }
640         return ""; //$NON-NLS-1$
641
}
642
643     /**
644      * Returns the name for the given element.
645      * Used as the name for the current frame.
646      */

647     String JavaDoc getFrameName(Object JavaDoc element) {
648         if (element instanceof IResource) {
649             return ((IResource) element).getName();
650         }
651         String JavaDoc text = ((ILabelProvider) getTreeViewer().getLabelProvider())
652         .getText(element);
653         if(text == null) {
654             return "";//$NON-NLS-1$
655
}
656         return text;
657     }
658
659     /**
660      * Returns the tool tip text for the given element.
661      * Used as the tool tip text for the current frame, and for the view title tooltip.
662      */

663     String JavaDoc getFrameToolTipText(Object JavaDoc element) {
664         if (element instanceof IResource) {
665             IPath path = ((IResource) element).getFullPath();
666             if (path.isRoot()) {
667                 return ResourceNavigatorMessages.ResourceManager_toolTip;
668             }
669             return path.makeRelative().toString();
670         }
671         
672         String JavaDoc text = ((ILabelProvider) getTreeViewer().getLabelProvider())
673             .getText(element);
674         if(text == null) {
675             return "";//$NON-NLS-1$
676
}
677         return text;
678     }
679
680     /**
681      * Handles an open event from the viewer.
682      * Opens an editor on the selected file.
683      *
684      * @param event the open event
685      * @since 2.0
686      */

687     protected void handleOpen(OpenEvent event) {
688         IStructuredSelection selection = (IStructuredSelection) event
689                 .getSelection();
690         getActionGroup().runDefaultAction(selection);
691     }
692
693     /**
694      * Handles a double-click event from the viewer.
695      * Expands or collapses a folder when double-clicked.
696      *
697      * @param event the double-click event
698      * @since 2.0
699      */

700     protected void handleDoubleClick(DoubleClickEvent event) {
701         IStructuredSelection selection = (IStructuredSelection) event
702                 .getSelection();
703         Object JavaDoc element = selection.getFirstElement();
704
705         // 1GBZIA0: ITPUI:WIN2000 - Double-clicking in navigator should expand/collapse containers
706
TreeViewer viewer = getTreeViewer();
707         if (viewer.isExpandable(element)) {
708             viewer.setExpandedState(element, !viewer.getExpandedState(element));
709         } else if (selection.size() == 1 && (element instanceof IResource)
710                 && ((IResource) element).getType() == IResource.PROJECT) {
711             OpenResourceAction ora = new OpenResourceAction(getSite()
712                     .getShell());
713             ora.selectionChanged((IStructuredSelection) viewer.getSelection());
714             if (ora.isEnabled()) {
715                 ora.run();
716             }
717         }
718
719     }
720
721     /**
722      * Handles a selection changed event from the viewer.
723      * Updates the status line and the action bars, and links to editor (if option enabled).
724      *
725      * @param event the selection event
726      * @since 2.0
727      */

728     protected void handleSelectionChanged(SelectionChangedEvent event) {
729         final IStructuredSelection sel = (IStructuredSelection) event
730                 .getSelection();
731         updateStatusLine(sel);
732         updateActionBars(sel);
733         dragDetected = false;
734         if (isLinkingEnabled() && !linkScheduled) {
735             // Ensure that if another selection change arrives while we're waiting for the *syncExec,
736
// we only do this work once.
737
linkScheduled = true;
738             getShell().getDisplay().asyncExec(new Runnable JavaDoc() {
739                 public void run() {
740                     // There's no telling what might have changed since the syncExec was scheduled.
741
// Check to make sure that the widgets haven't been disposed.
742
linkScheduled = false;
743                     
744                     if (viewer == null || viewer.getControl() == null || viewer.getControl().isDisposed()) {
745                         return;
746                     }
747                     
748                     if (dragDetected == false) {
749                         ISelection sel = viewer.getSelection();
750                         if (sel instanceof IStructuredSelection) {
751                             IStructuredSelection selection = (IStructuredSelection)sel;
752                         
753                             // only synchronize with editor when the selection is not the result
754
// of a drag. Fixes bug 22274.
755
linkToEditor(selection);
756                         }
757                     }
758                 }
759             });
760         }
761     }
762
763     /**
764      * Handles a key press event from the viewer.
765      * Delegates to the action group.
766      *
767      * @param event the key event
768      * @since 2.0
769      */

770     protected void handleKeyPressed(KeyEvent event) {
771         getActionGroup().handleKeyPressed(event);
772     }
773
774     /**
775      * Handles a key release in the viewer. Does nothing by default.
776      *
777      * @param event the key event
778      * @since 2.0
779      */

780     protected void handleKeyReleased(KeyEvent event) {
781     }
782
783     /* (non-Javadoc)
784      * Method declared on IViewPart.
785      */

786     public void init(IViewSite site, IMemento memento) throws PartInitException {
787         super.init(site, memento);
788         this.memento = memento;
789     }
790
791     /**
792      * Adds drag and drop support to the navigator.
793      *
794      * @since 2.0
795      */

796     protected void initDragAndDrop() {
797         int ops = DND.DROP_COPY | DND.DROP_MOVE;
798         Transfer[] transfers = new Transfer[] {
799                 LocalSelectionTransfer.getInstance(),
800                 ResourceTransfer.getInstance(), FileTransfer.getInstance(),
801                 PluginTransfer.getInstance() };
802         TreeViewer viewer = getTreeViewer();
803         viewer.addDragSupport(ops, transfers, new NavigatorDragAdapter(viewer));
804         NavigatorDropAdapter adapter = new NavigatorDropAdapter(viewer);
805         adapter.setFeedbackEnabled(false);
806         viewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, adapter);
807         dragDetectListener = new Listener() {
808             public void handleEvent(Event event) {
809                 dragDetected = true;
810             }
811         };
812         viewer.getControl().addListener(SWT.DragDetect, dragDetectListener);
813     }
814
815     /**
816      * Creates the frame source and frame list, and connects them.
817      *
818      * @since 2.0
819      */

820     protected FrameList createFrameList() {
821         NavigatorFrameSource frameSource = new NavigatorFrameSource(this);
822         FrameList frameList = new FrameList(frameSource);
823         frameSource.connectTo(frameList);
824         return frameList;
825     }
826
827     /**
828      * Initializes the sorter.
829      *
830      * @deprecated as of 3.3, use {@link ResourceNavigator#initResourceComparator()} instead
831      */

832     protected void initResourceSorter() {
833         int sortType = ResourceSorter.NAME;
834         try {
835             int sortInt = 0;
836             if (memento != null) {
837                 String JavaDoc sortStr = memento.getString(TAG_SORTER);
838                 if (sortStr != null) {
839                     sortInt = new Integer JavaDoc(sortStr).intValue();
840                 }
841             } else {
842                 sortInt = settings.getInt(STORE_SORT_TYPE);
843             }
844             if (sortInt == ResourceSorter.NAME
845                     || sortInt == ResourceSorter.TYPE) {
846                 sortType = sortInt;
847             }
848         } catch (NumberFormatException JavaDoc e) {
849         }
850         setSorter(new ResourceSorter(sortType));
851     }
852     
853     /**
854      * Initializes the comparator.
855      * @since 3.3
856      */

857     protected void initResourceComparator(){
858         int sortType = ResourceComparator.NAME;
859         try {
860             int sortInt = 0;
861             if (memento != null) {
862                 String JavaDoc sortStr = memento.getString(TAG_SORTER);
863                 if (sortStr != null) {
864                     sortInt = new Integer JavaDoc(sortStr).intValue();
865                 }
866             } else {
867                 sortInt = settings.getInt(STORE_SORT_TYPE);
868             }
869             if (sortInt == ResourceComparator.NAME
870                     || sortInt == ResourceComparator.TYPE) {
871                 sortType = sortInt;
872             }
873         } catch (NumberFormatException JavaDoc e) {
874         }
875         setComparator(new ResourceComparator(sortType));
876     }
877
878     /**
879      * Restores the working set filter from the persistence store.
880      */

881     protected void initWorkingSetFilter() {
882         String JavaDoc workingSetName = settings.get(STORE_WORKING_SET);
883
884         IWorkingSet workingSet = null;
885         
886         if (workingSetName != null && workingSetName.equals("") == false) { //$NON-NLS-1$
887
IWorkingSetManager workingSetManager = getPlugin().getWorkbench()
888                     .getWorkingSetManager();
889             workingSet = workingSetManager.getWorkingSet(workingSetName);
890         } else if (PlatformUI
891                 .getPreferenceStore()
892                 .getBoolean(
893                         IWorkbenchPreferenceConstants.USE_WINDOW_WORKING_SET_BY_DEFAULT)) {
894             // use the window set by default if the global preference is set
895
workingSet = getSite().getPage().getAggregateWorkingSet();
896         }
897
898         if (workingSet != null) {
899             // Only initialize filter. Don't set working set into viewer.
900
// Working set is set via WorkingSetFilterActionGroup
901
// during action creation.
902
workingSetFilter.setWorkingSet(workingSet);
903             internalSetWorkingSet(workingSet);
904         }
905     }
906
907     /**
908      * Returns whether the navigator selection automatically tracks the active
909      * editor.
910      *
911      * @return <code>true</code> if linking is enabled, <code>false</code>
912      * if not
913      * @since 2.0 (this was protected in 2.0, but was made public in 2.1)
914      */

915     public boolean isLinkingEnabled() {
916         return linkingEnabled;
917     }
918
919     /**
920      * Brings the corresponding editor to top if the selected resource is open.
921      *
922      * @since 2.0
923      */

924     protected void linkToEditor(IStructuredSelection selection) {
925
926         if (this != this.getSite().getPage().getActivePart())
927             return;
928         
929         Object JavaDoc obj = selection.getFirstElement();
930         if (obj instanceof IFile && selection.size() == 1) {
931             IFile file = (IFile) obj;
932             IWorkbenchPage page = getSite().getPage();
933             IEditorPart editor = ResourceUtil.findEditor(page, file);
934             if (editor != null) {
935                 page.bringToTop(editor);
936                 return;
937             }
938         }
939     }
940
941     /**
942      * Creates the action group, which encapsulates all actions for the view.
943      */

944     protected void makeActions() {
945         setActionGroup(new MainActionGroup(this));
946     }
947
948     /**
949      * Restores the saved filter settings.
950      */

951     private void restoreFilters() {
952         IMemento filtersMem = memento.getChild(TAG_FILTERS);
953
954         if (filtersMem != null) { //filters have been defined
955
IMemento children[] = filtersMem.getChildren(TAG_FILTER);
956
957             // check if first element has new tag defined, indicates new version
958
if (children.length > 0
959                     && children[0].getString(TAG_IS_ENABLED) != null) {
960                 ArrayList JavaDoc selectedFilters = new ArrayList JavaDoc();
961                 ArrayList JavaDoc unSelectedFilters = new ArrayList JavaDoc();
962                 for (int i = 0; i < children.length; i++) {
963                     if (children[i].getString(TAG_IS_ENABLED).equals(
964                             String.valueOf(true))) {
965                         selectedFilters.add(children[i].getString(TAG_ELEMENT));
966                     } else {
967                         //enabled == false
968
unSelectedFilters.add(children[i]
969                                 .getString(TAG_ELEMENT));
970                     }
971                 }
972
973                 /* merge filters from Memento with selected = true filters from plugins
974                  * ensure there are no duplicates & don't override user preferences */

975                 List JavaDoc pluginFilters = FiltersContentProvider.getDefaultFilters();
976                 for (Iterator JavaDoc iter = pluginFilters.iterator(); iter.hasNext();) {
977                     String JavaDoc element = (String JavaDoc) iter.next();
978                     if (!selectedFilters.contains(element)
979                             && !unSelectedFilters.contains(element)) {
980                         selectedFilters.add(element);
981                     }
982                 }
983
984                 //Convert to an array of Strings
985
String JavaDoc[] patternArray = new String JavaDoc[selectedFilters.size()];
986                 selectedFilters.toArray(patternArray);
987                 getPatternFilter().setPatterns(patternArray);
988
989             } else { //filters defined, old version: ignore filters from plugins
990
String JavaDoc filters[] = new String JavaDoc[children.length];
991                 for (int i = 0; i < children.length; i++) {
992                     filters[i] = children[i].getString(TAG_ELEMENT);
993                 }
994                 getPatternFilter().setPatterns(filters);
995             }
996         } else { //no filters defined, old version: ignore filters from plugins
997
getPatternFilter().setPatterns(new String JavaDoc[0]);
998         }
999     }
1000
1001    /**
1002     * Restores the state of the receiver to the state described in the specified memento.
1003     *
1004     * @param memento the memento
1005     * @since 2.0
1006     */

1007    protected void restoreState(IMemento memento) {
1008        TreeViewer viewer = getTreeViewer();
1009        IMemento frameMemento = memento.getChild(TAG_CURRENT_FRAME);
1010
1011        if (frameMemento != null) {
1012            TreeFrame frame = new TreeFrame(viewer);
1013            frame.restoreState(frameMemento);
1014            frame.setName(getFrameName(frame.getInput()));
1015            frame.setToolTipText(getFrameToolTipText(frame.getInput()));
1016            viewer.setSelection(new StructuredSelection(frame.getInput()));
1017            frameList.gotoFrame(frame);
1018        } else {
1019            IContainer container = ResourcesPlugin.getWorkspace().getRoot();
1020            IMemento childMem = memento.getChild(TAG_EXPANDED);
1021            if (childMem != null) {
1022                ArrayList JavaDoc elements = new ArrayList JavaDoc();
1023                IMemento[] elementMem = childMem.getChildren(TAG_ELEMENT);
1024                for (int i = 0; i < elementMem.length; i++) {
1025                    Object JavaDoc element = container.findMember(elementMem[i]
1026                            .getString(TAG_PATH));
1027                    if (element != null) {
1028                        elements.add(element);
1029                    }
1030                }
1031                viewer.setExpandedElements(elements.toArray());
1032            }
1033            childMem = memento.getChild(TAG_SELECTION);
1034            if (childMem != null) {
1035                ArrayList JavaDoc list = new ArrayList JavaDoc();
1036                IMemento[] elementMem = childMem.getChildren(TAG_ELEMENT);
1037                for (int i = 0; i < elementMem.length; i++) {
1038                    Object JavaDoc element = container.findMember(elementMem[i]
1039                            .getString(TAG_PATH));
1040                    if (element != null) {
1041                        list.add(element);
1042                    }
1043                }
1044                viewer.setSelection(new StructuredSelection(list));
1045            }
1046        }
1047    }
1048
1049    /**
1050     * Restores the linking enabled state.
1051     */

1052    private void restoreLinkingEnabled() {
1053        Integer JavaDoc val = memento
1054                .getInteger(IWorkbenchPreferenceConstants.LINK_NAVIGATOR_TO_EDITOR);
1055        if (val != null) {
1056            linkingEnabled = val.intValue() != 0;
1057        }
1058    }
1059
1060    /**
1061     * @see ViewPart#saveState
1062     */

1063    public void saveState(IMemento memento) {
1064        TreeViewer viewer = getTreeViewer();
1065        if (viewer == null) {
1066            if (this.memento != null) {
1067                memento.putMemento(this.memento);
1068            }
1069            return;
1070        }
1071
1072        //save sorter
1073
memento.putInteger(TAG_SORTER, getComparator().getCriteria());
1074
1075        //save filters
1076
String JavaDoc filters[] = getPatternFilter().getPatterns();
1077        List JavaDoc selectedFilters = Arrays.asList(filters);
1078        List JavaDoc allFilters = FiltersContentProvider.getDefinedFilters();
1079        IMemento filtersMem = memento.createChild(TAG_FILTERS);
1080        for (Iterator JavaDoc iter = allFilters.iterator(); iter.hasNext();) {
1081            String JavaDoc element = (String JavaDoc) iter.next();
1082            IMemento child = filtersMem.createChild(TAG_FILTER);
1083            child.putString(TAG_ELEMENT, element);
1084            child.putString(TAG_IS_ENABLED, String.valueOf(selectedFilters
1085                    .contains(element)));
1086        }
1087
1088        if (frameList.getCurrentIndex() > 0) {
1089            //save frame, it's not the "home"/workspace frame
1090
TreeFrame currentFrame = (TreeFrame) frameList.getCurrentFrame();
1091            IMemento frameMemento = memento.createChild(TAG_CURRENT_FRAME);
1092            currentFrame.saveState(frameMemento);
1093        } else {
1094            //save visible expanded elements
1095
Object JavaDoc expandedElements[] = viewer.getVisibleExpandedElements();
1096            if (expandedElements.length > 0) {
1097                IMemento expandedMem = memento.createChild(TAG_EXPANDED);
1098                for (int i = 0; i < expandedElements.length; i++) {
1099                    if (expandedElements[i] instanceof IResource) {
1100                        IMemento elementMem = expandedMem
1101                                .createChild(TAG_ELEMENT);
1102                        elementMem.putString(TAG_PATH,
1103                                ((IResource) expandedElements[i]).getFullPath()
1104                                        .toString());
1105                    }
1106                }
1107            }
1108            //save selection
1109
Object JavaDoc elements[] = ((IStructuredSelection) viewer.getSelection())
1110                    .toArray();
1111            if (elements.length > 0) {
1112                IMemento selectionMem = memento.createChild(TAG_SELECTION);
1113                for (int i = 0; i < elements.length; i++) {
1114                    if (elements[i] instanceof IResource) {
1115                        IMemento elementMem = selectionMem
1116                                .createChild(TAG_ELEMENT);
1117                        elementMem.putString(TAG_PATH,
1118                                ((IResource) elements[i]).getFullPath()
1119                                        .toString());
1120                    }
1121                }
1122            }
1123        }
1124
1125        saveLinkingEnabled(memento);
1126    }
1127
1128    /**
1129     * Saves the linking enabled state.
1130     */

1131    private void saveLinkingEnabled(IMemento memento) {
1132        memento.putInteger(
1133                IWorkbenchPreferenceConstants.LINK_NAVIGATOR_TO_EDITOR,
1134                linkingEnabled ? 1 : 0);
1135    }
1136
1137    /**
1138     * Selects and reveals the specified elements.
1139     */

1140    public void selectReveal(ISelection selection) {
1141        StructuredSelection ssel = convertSelection(selection);
1142        if (!ssel.isEmpty()) {
1143            getViewer().getControl().setRedraw(false);
1144            getViewer().setSelection(ssel, true);
1145            getViewer().getControl().setRedraw(true);
1146        }
1147    }
1148
1149    /**
1150     * Saves the filters defined as strings in <code>patterns</code>
1151     * in the preference store.
1152     */

1153    public void setFiltersPreference(String JavaDoc[] patterns) {
1154
1155        StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1156
1157        for (int i = 0; i < patterns.length; i++) {
1158            if (i != 0) {
1159                sb.append(ResourcePatternFilter.COMMA_SEPARATOR);
1160            }
1161            sb.append(patterns[i]);
1162        }
1163
1164        getPlugin().getPreferenceStore().setValue(
1165                ResourcePatternFilter.FILTERS_TAG, sb.toString());
1166
1167        // remove value in old workbench preference store location
1168
IPreferenceStore preferenceStore = IDEWorkbenchPlugin.getDefault()
1169                .getPreferenceStore();
1170        String JavaDoc storedPatterns = preferenceStore
1171                .getString(ResourcePatternFilter.FILTERS_TAG);
1172        if (storedPatterns.length() > 0) {
1173            preferenceStore.setValue(ResourcePatternFilter.FILTERS_TAG, ""); //$NON-NLS-1$
1174
}
1175    }
1176
1177    /**
1178     * @see IWorkbenchPart#setFocus()
1179     */

1180    public void setFocus() {
1181        getTreeViewer().getTree().setFocus();
1182    }
1183
1184    /**
1185     * Note: For experimental use only.
1186     * Sets the decorator for the navigator.
1187     * <p>
1188     * As of 2.0, this method no longer has any effect.
1189     * </p>
1190     *
1191     * @param decorator a label decorator or <code>null</code> for no decorations.
1192     * @deprecated use the decorators extension point instead; see IWorkbench.getDecoratorManager()
1193     */

1194    public void setLabelDecorator(ILabelDecorator decorator) {
1195        // do nothing
1196
}
1197
1198    /**
1199     * @see IResourceNavigator#setLinkingEnabled(boolean)
1200     * @since 2.1
1201     */

1202    public void setLinkingEnabled(boolean enabled) {
1203        this.linkingEnabled = enabled;
1204
1205        // remember the last setting in the dialog settings
1206
settings.put(IWorkbenchPreferenceConstants.LINK_NAVIGATOR_TO_EDITOR,
1207                enabled);
1208
1209        // if turning linking on, update the selection to correspond to the active editor
1210
if (enabled) {
1211            IEditorPart editor = getSite().getPage().getActiveEditor();
1212            if (editor != null) {
1213                editorActivated(editor);
1214            }
1215        }
1216    }
1217
1218    /**
1219     * Sets the resource sorter.
1220     *
1221     * @param sorter the resource sorter
1222     * @since 2.0
1223     * @deprecated as of 3.3, use {@link ResourceNavigator#setComparator(ResourceComparator)}
1224     */

1225    public void setSorter(ResourceSorter sorter) {
1226        TreeViewer viewer = getTreeViewer();
1227        ViewerSorter viewerSorter = viewer.getSorter();
1228
1229        viewer.getControl().setRedraw(false);
1230        if (viewerSorter == sorter) {
1231            viewer.refresh();
1232        } else {
1233            viewer.setSorter(sorter);
1234        }
1235        viewer.getControl().setRedraw(true);
1236        settings.put(STORE_SORT_TYPE, sorter.getCriteria());
1237
1238        // update the sort actions' checked state
1239
updateActionBars((IStructuredSelection) viewer.getSelection());
1240    }
1241    
1242    /**
1243     * Sets the resource comparator
1244     *
1245     * @param comparator the resource comparator
1246     * @since 3.3
1247     */

1248    public void setComparator(ResourceComparator comparator){
1249        TreeViewer viewer = getTreeViewer();
1250        ViewerComparator viewerComparator = viewer.getComparator();
1251
1252        viewer.getControl().setRedraw(false);
1253        if (viewerComparator == comparator) {
1254            viewer.refresh();
1255        } else {
1256            viewer.setComparator(comparator);
1257        }
1258        viewer.getControl().setRedraw(true);
1259        settings.put(STORE_SORT_TYPE, comparator.getCriteria());
1260
1261        // update the sort actions' checked state
1262
updateActionBars((IStructuredSelection) viewer.getSelection());
1263    }
1264
1265    /*
1266     * @see org.eclipse.ui.views.navigator.IResourceNavigatorPart#setWorkingSet(IWorkingSet)
1267     * @since 2.0
1268     */

1269    public void setWorkingSet(IWorkingSet workingSet) {
1270        TreeViewer treeViewer = getTreeViewer();
1271        Object JavaDoc[] expanded = treeViewer.getExpandedElements();
1272        ISelection selection = treeViewer.getSelection();
1273        
1274        internalSetWorkingSet(workingSet);
1275        
1276        workingSetFilter.setWorkingSet(emptyWorkingSet ? null : workingSet);
1277        if (workingSet != null) {
1278            settings.put(STORE_WORKING_SET, workingSet.getName());
1279        } else {
1280            settings.put(STORE_WORKING_SET, ""); //$NON-NLS-1$
1281
}
1282        updateTitle();
1283        treeViewer.refresh();
1284        treeViewer.setExpandedElements(expanded);
1285        if (selection.isEmpty() == false
1286                && selection instanceof IStructuredSelection) {
1287            IStructuredSelection structuredSelection = (IStructuredSelection) selection;
1288            treeViewer.reveal(structuredSelection.getFirstElement());
1289        }
1290    }
1291
1292    /**
1293     * Set the internal working set fields specific to the navigator.
1294     *
1295     * @param workingSet
1296     * the new working set
1297     * @since 3.2
1298     */

1299    private void internalSetWorkingSet(IWorkingSet workingSet) {
1300        this.workingSet = workingSet;
1301        emptyWorkingSet = workingSet != null && workingSet.isAggregateWorkingSet()
1302                && workingSet.isEmpty();
1303    }
1304
1305    /**
1306     * Updates the action bar actions.
1307     *
1308     * @param selection the current selection
1309     * @since 2.0
1310     */

1311    protected void updateActionBars(IStructuredSelection selection) {
1312        ResourceNavigatorActionGroup group = getActionGroup();
1313        if (group != null) {
1314            group.setContext(new ActionContext(selection));
1315            group.updateActionBars();
1316        }
1317    }
1318
1319    /**
1320     * Updates the message shown in the status line.
1321     *
1322     * @param selection the current selection
1323     */

1324    protected void updateStatusLine(IStructuredSelection selection) {
1325        String JavaDoc msg = getStatusLineMessage(selection);
1326        getViewSite().getActionBars().getStatusLineManager().setMessage(msg);
1327    }
1328
1329    /**
1330     * Updates the title text and title tool tip.
1331     * Called whenever the input of the viewer changes.
1332     * Called whenever the input of the viewer changes.
1333     *
1334     * @since 2.0
1335     */

1336    public void updateTitle() {
1337        Object JavaDoc input = getViewer().getInput();
1338        IWorkspace workspace = ResourcesPlugin.getWorkspace();
1339        IWorkingSet workingSet = workingSetFilter.getWorkingSet();
1340
1341        if (input == null || input.equals(workspace)
1342                || input.equals(workspace.getRoot())) {
1343            setContentDescription(""); //$NON-NLS-1$
1344
if (workingSet != null) {
1345                setTitleToolTip(NLS.bind(ResourceNavigatorMessages.ResourceNavigator_workingSetToolTip, workingSet.getLabel()));
1346            } else {
1347                setTitleToolTip(""); //$NON-NLS-1$
1348
}
1349        } else {
1350            ILabelProvider labelProvider = (ILabelProvider) getTreeViewer()
1351                    .getLabelProvider();
1352            String JavaDoc inputToolTip = getFrameToolTipText(input);
1353            String JavaDoc text = labelProvider.getText(input);
1354            if(text != null) {
1355                setContentDescription(text);
1356            }
1357            if (workingSet != null) {
1358                setTitleToolTip(NLS.bind(ResourceNavigatorMessages.ResourceNavigator_workingSetInputToolTip, inputToolTip, workingSet.getLabel()));
1359            } else {
1360                setTitleToolTip(inputToolTip);
1361            }
1362        }
1363    }
1364
1365    /**
1366     * Returns the action group.
1367     *
1368     * @return the action group
1369     */

1370    protected ResourceNavigatorActionGroup getActionGroup() {
1371        return actionGroup;
1372    }
1373
1374    /**
1375     * Sets the action group.
1376     *
1377     * @param actionGroup the action group
1378     */

1379    protected void setActionGroup(ResourceNavigatorActionGroup actionGroup) {
1380        this.actionGroup = actionGroup;
1381    }
1382
1383    /*
1384     * @see IWorkbenchPart#getAdapter(Class)
1385     */

1386    public Object JavaDoc getAdapter(Class JavaDoc adapter) {
1387        if (adapter == IShowInSource.class) {
1388            return getShowInSource();
1389        }
1390        if (adapter == IShowInTarget.class) {
1391            return getShowInTarget();
1392        }
1393        return null;
1394    }
1395
1396    /**
1397     * Returns the <code>IShowInSource</code> for this view.
1398     */

1399    protected IShowInSource getShowInSource() {
1400        return new IShowInSource() {
1401            public ShowInContext getShowInContext() {
1402                return new ShowInContext(getViewer().getInput(), getViewer()
1403                        .getSelection());
1404            }
1405        };
1406    }
1407
1408    /**
1409     * Returns the <code>IShowInTarget</code> for this view.
1410     */

1411    protected IShowInTarget getShowInTarget() {
1412        return new IShowInTarget() {
1413            public boolean show(ShowInContext context) {
1414                ArrayList JavaDoc toSelect = new ArrayList JavaDoc();
1415                ISelection sel = context.getSelection();
1416                if (sel instanceof IStructuredSelection) {
1417                    IStructuredSelection ssel = (IStructuredSelection) sel;
1418                    for (Iterator JavaDoc i = ssel.iterator(); i.hasNext();) {
1419                        Object JavaDoc o = i.next();
1420                        if (o instanceof IResource) {
1421                            toSelect.add(o);
1422                        } else if (o instanceof IMarker) {
1423                            IResource r = ((IMarker) o).getResource();
1424                            if (r.getType() != IResource.ROOT) {
1425                                toSelect.add(r);
1426                            }
1427                        } else if (o instanceof IAdaptable) {
1428                            IAdaptable adaptable = (IAdaptable) o;
1429                            o = adaptable.getAdapter(IResource.class);
1430                            if (o instanceof IResource) {
1431                                toSelect.add(o);
1432                            } else {
1433                                o = adaptable.getAdapter(IMarker.class);
1434                                if (o instanceof IMarker) {
1435                                    IResource r = ((IMarker) o).getResource();
1436                                    if (r.getType() != IResource.ROOT) {
1437                                        toSelect.add(r);
1438                                    }
1439                                }
1440                            }
1441                        }
1442                    }
1443                }
1444                if (toSelect.isEmpty()) {
1445                    Object JavaDoc input = context.getInput();
1446                    if (input instanceof IAdaptable) {
1447                        IAdaptable adaptable = (IAdaptable) input;
1448                        Object JavaDoc o = adaptable.getAdapter(IResource.class);
1449                        if (o instanceof IResource) {
1450                            toSelect.add(o);
1451                        }
1452                    }
1453                }
1454                if (!toSelect.isEmpty()) {
1455                    selectReveal(new StructuredSelection(toSelect));
1456                    return true;
1457                }
1458                return false;
1459            }
1460        };
1461    }
1462}
1463
Popular Tags