KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > team > internal > ui > mapping > CommonViewerAdvisor


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.team.internal.ui.mapping;
12
13 import java.util.*;
14
15 import org.eclipse.core.resources.mapping.*;
16 import org.eclipse.core.runtime.CoreException;
17 import org.eclipse.jface.action.*;
18 import org.eclipse.jface.util.IPropertyChangeListener;
19 import org.eclipse.jface.util.PropertyChangeEvent;
20 import org.eclipse.jface.viewers.*;
21 import org.eclipse.osgi.util.NLS;
22 import org.eclipse.swt.SWT;
23 import org.eclipse.swt.layout.GridData;
24 import org.eclipse.swt.widgets.*;
25 import org.eclipse.team.core.TeamException;
26 import org.eclipse.team.core.mapping.*;
27 import org.eclipse.team.internal.ui.TeamUIPlugin;
28 import org.eclipse.team.internal.ui.Utils;
29 import org.eclipse.team.internal.ui.synchronize.AbstractTreeViewerAdvisor;
30 import org.eclipse.team.internal.ui.synchronize.SynchronizePageConfiguration;
31 import org.eclipse.team.ui.TeamUI;
32 import org.eclipse.team.ui.mapping.*;
33 import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration;
34 import org.eclipse.team.ui.synchronize.ModelSynchronizeParticipant;
35 import org.eclipse.ui.*;
36 import org.eclipse.ui.actions.ActionContext;
37 import org.eclipse.ui.navigator.*;
38 import org.eclipse.ui.navigator.resources.ResourceDragAdapterAssistant;
39 import org.eclipse.ui.part.IPageSite;
40
41 /**
42  * Provides a Common Navigator based viewer for use by a {@link ModelSynchronizePage}.
43  */

44 public class CommonViewerAdvisor extends AbstractTreeViewerAdvisor implements INavigatorContentServiceListener, IEmptyTreeListener, IPropertyChangeListener {
45
46     public static final class NavigableCommonViewer extends CommonViewer implements ITreeViewerAccessor {
47         private final IEmptyTreeListener listener;
48         private boolean empty;
49         private NavigableCommonViewer(String JavaDoc id, Composite parent, int style, IEmptyTreeListener listener) {
50             super(id, parent, style);
51             this.listener = listener;
52         }
53         public void createChildren(TreeItem item) {
54             super.createChildren(item);
55         }
56         public void openSelection() {
57             fireOpen(new OpenEvent(this, getSelection()));
58         }
59         protected void internalRefresh(Object JavaDoc element, boolean updateLabels) {
60             TreePath[] expanded = getVisibleExpandedPaths();
61             super.internalRefresh(element, updateLabels);
62             setExpandedTreePaths(expanded);
63             checkForEmptyViewer();
64         }
65         protected void internalRemove(Object JavaDoc parent, Object JavaDoc[] elements) {
66             super.internalRemove(parent, elements);
67             if (parent == getInput())
68                 checkForEmptyViewer();
69         }
70         protected void internalRemove(Object JavaDoc[] elements) {
71             super.internalRemove(elements);
72             checkForEmptyViewer();
73         }
74         protected void internalAdd(Widget widget, Object JavaDoc parentElement, Object JavaDoc[] childElements) {
75             super.internalAdd(widget, parentElement, childElements);
76             if (empty) {
77                 empty = false;
78                 listener.notEmpty(this);
79             }
80                 
81         }
82         protected void inputChanged(Object JavaDoc input, Object JavaDoc oldInput) {
83             super.inputChanged(input, oldInput);
84             checkForEmptyViewer();
85         }
86         private void checkForEmptyViewer() {
87             Object JavaDoc input = getInput();
88             if (input != null) {
89                 Widget w = findItem(input);
90                 Item[] children = getChildren(w);
91                 if (children.length == 0) {
92                     if (!empty) {
93                         empty = true;
94                         listener.treeEmpty(this);
95                     }
96                     return;
97                 }
98             }
99             empty = false;
100             if (listener != null)
101                 listener.notEmpty(this);
102         }
103         public boolean isEmpty() {
104             return empty;
105         }
106         
107         protected void initDragAndDrop() {
108             getNavigatorContentService().getDnDService().bindDragAssistant(new ResourceDragAdapterAssistant());
109             super.initDragAndDrop();
110         }
111         /**
112          * Gets the expanded elements that are visible to the user. An expanded
113          * element is only visible if the parent is expanded.
114          *
115          * @return the visible expanded elements
116          * @since 2.0
117          */

118         public TreePath[] getVisibleExpandedPaths() {
119             ArrayList v = new ArrayList();
120             internalCollectVisibleExpanded(v, getControl());
121             return (TreePath[]) v.toArray(new TreePath[v.size()]);
122         }
123
124         private void internalCollectVisibleExpanded(ArrayList result, Widget widget) {
125             Item[] items = getChildren(widget);
126             for (int i = 0; i < items.length; i++) {
127                 Item item = items[i];
128                 if (getExpanded(item)) {
129                     TreePath path = getTreePathFromItem(item);
130                     if (path != null) {
131                         result.add(path);
132                     }
133                     //Only recurse if it is expanded - if
134
//not then the children aren't visible
135
internalCollectVisibleExpanded(result, item);
136                 }
137             }
138         }
139     }
140
141     /**
142      * Subclass of SubActionBars that manages the contributions from the common action service
143      */

144     private class CommonSubActionBars extends SubActionBars {
145
146         public CommonSubActionBars(IActionBars parent) {
147             super(parent);
148         }
149         
150         public void setGlobalActionHandler(String JavaDoc actionID, IAction handler) {
151             if (handler == null) {
152                 // Only remove the handler if it was set
153
if (getGlobalActionHandler(actionID) != null) {
154                     getParent().setGlobalActionHandler(actionID, null);
155                     super.setGlobalActionHandler(actionID, null);
156                 }
157             } else {
158                 // Only set the action handler if the parent doesn't
159
if (getParent().getGlobalActionHandler(actionID) != null) {
160                     TeamUIPlugin.log(new TeamException(NLS.bind("Conflicting attempt to set action id {0} detected", actionID))); //$NON-NLS-1$
161
return;
162                 }
163                 super.setGlobalActionHandler(actionID, handler);
164             }
165         }
166         
167         public void clearGlobalActionHandlers() {
168             // When cleared, also remove the ids from the parent
169
Map handlers = getGlobalActionHandlers();
170             if (handlers != null) {
171                 Set keys = handlers.keySet();
172                 Iterator iter = keys.iterator();
173                 while (iter.hasNext()) {
174                     String JavaDoc actionId = (String JavaDoc) iter.next();
175                     getParent().setGlobalActionHandler(actionId,
176                             null);
177                 }
178             }
179             super.clearGlobalActionHandlers();
180         }
181         
182         public void updateActionBars() {
183             // On update, push all or action handlers into our parent
184
Map newActionHandlers = getGlobalActionHandlers();
185             if (newActionHandlers != null) {
186                 Set keys = newActionHandlers.entrySet();
187                 Iterator iter = keys.iterator();
188                 while (iter.hasNext()) {
189                     Map.Entry entry = (Map.Entry) iter.next();
190                     getParent().setGlobalActionHandler((String JavaDoc) entry.getKey(),
191                             (IAction) entry.getValue());
192                 }
193             }
194             super.updateActionBars();
195         }
196         
197     }
198     
199     public static final String JavaDoc TEAM_NAVIGATOR_CONTENT = "org.eclipse.team.ui.navigatorViewer"; //$NON-NLS-1$
200

201     private static final String JavaDoc PROP_ACTION_SERVICE_ACTION_BARS = "org.eclipse.team.ui.actionServiceActionBars"; //$NON-NLS-1$
202

203     private Set extensions = new HashSet();
204     
205     private NavigatorActionService actionService;
206
207     private IEmptyTreeListener emptyTreeListener;
208     
209     /**
210      * Create a common viewer
211      * @param parent the parent composite of the common viewer
212      * @param configuration the configuration for the viewer
213      * @return a newly created common viewer
214      */

215     private static CommonViewer createViewer(Composite parent, final ISynchronizePageConfiguration configuration, IEmptyTreeListener listener) {
216         final CommonViewer v = new NavigableCommonViewer(configuration.getViewerId(), parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL, listener);
217         v.setSorter(new CommonViewerSorter());
218         v.setSorter(new TeamViewerSorter((CommonViewerSorter)v.getSorter()));
219         ISynchronizationScope scope = getScope(configuration);
220         bindTeamContentProviders(v);
221         scope.addScopeChangeListener(new ISynchronizationScopeChangeListener() {
222             public void scopeChanged(final ISynchronizationScope scope,
223                     ResourceMapping[] newMappings, ResourceTraversal[] newTraversals) {
224                 enableContentProviders(v, configuration);
225                 Utils.asyncExec(new Runnable JavaDoc() {
226                     public void run() {
227                         v.refresh();
228                     }
229                 
230                 }, v);
231             }
232         });
233         enableContentProviders(v, configuration);
234         configuration.getSite().setSelectionProvider(v);
235         return v;
236     }
237
238     private static void enableContentProviders(CommonViewer v, ISynchronizePageConfiguration configuration) {
239         v.getNavigatorContentService().getActivationService().activateExtensions(getEnabledContentProviders(configuration), true);
240     }
241
242     private static String JavaDoc[] getEnabledContentProviders(ISynchronizePageConfiguration configuration) {
243         String JavaDoc visibleModel = (String JavaDoc)configuration.getProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER);
244         if (visibleModel != null && !visibleModel.equals(ModelSynchronizeParticipant.ALL_MODEL_PROVIDERS_VISIBLE)) {
245             ITeamContentProviderDescriptor desc = TeamUI.getTeamContentProviderManager().getDescriptor(visibleModel);
246             if (desc != null && desc.isEnabled())
247                 return new String JavaDoc[] { desc.getContentExtensionId() };
248         }
249         configuration.setProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER, ModelSynchronizeParticipant.ALL_MODEL_PROVIDERS_VISIBLE);
250         ModelSynchronizeParticipant participant = (ModelSynchronizeParticipant)configuration.getParticipant();
251         ModelProvider[] providers = participant.getEnabledModelProviders();
252         Set result = new HashSet();
253         Object JavaDoc property = configuration.getProperty(ITeamContentProviderManager.PROP_PAGE_LAYOUT);
254         boolean isFlatLayout = property != null && property.equals(ITeamContentProviderManager.FLAT_LAYOUT);
255         for (int i = 0; i < providers.length; i++) {
256             ModelProvider provider = providers[i];
257             ITeamContentProviderDescriptor desc = TeamUI.getTeamContentProviderManager().getDescriptor(provider.getId());
258             if (desc != null && desc.isEnabled() && (!isFlatLayout || desc.isFlatLayoutSupported()))
259                 result.add(desc.getContentExtensionId());
260         }
261         return (String JavaDoc[]) result.toArray(new String JavaDoc[result.size()]);
262     }
263
264     private static void bindTeamContentProviders(CommonViewer v) {
265         ITeamContentProviderManager teamContentProviderManager = TeamUI.getTeamContentProviderManager();
266         ITeamContentProviderDescriptor[] descriptors = teamContentProviderManager.getDescriptors();
267         Set toBind = new HashSet();
268         for (int i = 0; i < descriptors.length; i++) {
269             ITeamContentProviderDescriptor descriptor = descriptors[i];
270             toBind.add(descriptor.getContentExtensionId());
271         }
272         v.getNavigatorContentService().bindExtensions((String JavaDoc[]) toBind.toArray(new String JavaDoc[toBind.size()]), true);
273     }
274     
275     private static ISynchronizationScope getScope(ISynchronizePageConfiguration configuration) {
276         return (ISynchronizationScope)configuration.getProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_SCOPE);
277     }
278
279     /**
280      * Create the advisor using the given configuration
281      * @param parent the parent
282      * @param configuration the configuration
283      */

284     public CommonViewerAdvisor(Composite parent, ISynchronizePageConfiguration configuration) {
285         super(configuration);
286         final CommonViewer viewer = CommonViewerAdvisor.createViewer(parent, configuration, this);
287         TeamUI.getTeamContentProviderManager().addPropertyChangeListener(this);
288         configuration.addPropertyChangeListener(this);
289         GridData data = new GridData(GridData.FILL_BOTH);
290         viewer.getControl().setLayoutData(data);
291         viewer.getNavigatorContentService().addListener(this);
292         initializeViewer(viewer);
293         IBaseLabelProvider provider = viewer.getLabelProvider();
294         if (provider instanceof DecoratingLabelProvider) {
295             DecoratingLabelProvider dlp = (DecoratingLabelProvider) provider;
296             ILabelDecorator decorator = ((SynchronizePageConfiguration)configuration).getLabelDecorator();
297             if (decorator != null) {
298                 ILabelProvider lp = dlp.getLabelProvider();
299                 dlp = new DecoratingLabelProvider(
300                         new DecoratingLabelProvider(lp, decorator),
301                         PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator());
302                 viewer.setLabelProvider(dlp);
303             }
304             DecorationContext decorationContext = new DecorationContext();
305             decorationContext.putProperty(SynchronizationStateTester.PROP_TESTER, new SynchronizationStateTester() {
306                 public boolean isStateDecorationEnabled() {
307                     return false;
308                 }
309             });
310             dlp.setDecorationContext(decorationContext);
311         }
312         viewer.setInput(getInitialInput());
313         viewer.expandToLevel(2);
314     }
315
316     /* (non-Javadoc)
317      * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#initializeViewer(org.eclipse.jface.viewers.StructuredViewer)
318      */

319     public void initializeViewer(StructuredViewer viewer) {
320         createActionService((CommonViewer)viewer, getConfiguration());
321         super.initializeViewer(viewer);
322     }
323     
324     private void createActionService(CommonViewer viewer, ISynchronizePageConfiguration configuration) {
325         ICommonViewerSite commonSite = createCommonViewerSite(viewer, configuration);
326         actionService = new NavigatorActionService(commonSite, viewer, viewer.getNavigatorContentService());
327     }
328
329     private ICommonViewerSite createCommonViewerSite(CommonViewer viewer, ISynchronizePageConfiguration configuration) {
330         IWorkbenchSite site = configuration.getSite().getWorkbenchSite();
331         if (site instanceof IEditorSite) {
332             IEditorSite es = (IEditorSite) site;
333             return CommonViewerSiteFactory.createCommonViewerSite(es);
334         }
335         if (site instanceof IViewSite) {
336             IViewSite vs = (IViewSite) site;
337             return CommonViewerSiteFactory.createCommonViewerSite(vs);
338         }
339         if (site instanceof IPageSite) {
340             IPageSite ps = (IPageSite) site;
341             return CommonViewerSiteFactory.createCommonViewerSite(configuration.getViewerId(), ps);
342         }
343         return CommonViewerSiteFactory.createCommonViewerSite(configuration.getViewerId(), viewer, configuration.getSite().getShell());
344     }
345
346     private Object JavaDoc getInitialInput() {
347         String JavaDoc visible = (String JavaDoc)getConfiguration().getProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER);
348         if (visible != null && !visible.equals(ModelSynchronizeParticipant.ALL_MODEL_PROVIDERS_VISIBLE)) {
349             try {
350                 IModelProviderDescriptor desc = ModelProvider.getModelProviderDescriptor(visible);
351                 if (desc != null)
352                     return desc.getModelProvider();
353             } catch (CoreException e) {
354                 TeamUIPlugin.log(e);
355             }
356         }
357         return getConfiguration().getProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_CONTEXT);
358     }
359     
360     /* (non-Javadoc)
361      * @see org.eclipse.ui.navigator.internal.extensions.INavigatorContentServiceListener#onLoad(org.eclipse.ui.navigator.internal.extensions.NavigatorContentExtension)
362      */

363     public void onLoad(INavigatorContentExtension anExtension) {
364         extensions.add(anExtension);
365         ISynchronizationContext context = getParticipant().getContext();
366         anExtension.getStateModel().setProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_SCOPE, context.getScope());
367         anExtension.getStateModel().setProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_PAGE_CONFIGURATION, getConfiguration());
368         anExtension.getStateModel().setProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_CONTEXT, context);
369     }
370
371     private ModelSynchronizeParticipant getParticipant() {
372         return (ModelSynchronizeParticipant)getConfiguration().getParticipant();
373     }
374     
375     /* (non-Javadoc)
376      * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#getContextMenuId(org.eclipse.jface.viewers.StructuredViewer)
377      */

378     protected String JavaDoc getContextMenuId(StructuredViewer viewer) {
379         return ((CommonViewer)viewer).getNavigatorContentService().getViewerDescriptor().getPopupMenuId();
380     }
381     
382     /* (non-Javadoc)
383      * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#registerContextMenu(org.eclipse.jface.viewers.StructuredViewer, org.eclipse.jface.action.MenuManager)
384      */

385     protected void registerContextMenu(StructuredViewer viewer, MenuManager menuMgr) {
386         actionService.prepareMenuForPlatformContributions(menuMgr,
387                 viewer, false);
388     }
389     
390     /* (non-Javadoc)
391      * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#fillContextMenu(org.eclipse.jface.viewers.StructuredViewer, org.eclipse.jface.action.IMenuManager)
392      */

393     protected void fillContextMenu(StructuredViewer viewer, IMenuManager manager) {
394         // Clear any handlers from the menu
395
if (manager instanceof CommonMenuManager) {
396             CommonMenuManager cmm = (CommonMenuManager) manager;
397             cmm.clearHandlers();
398         }
399         
400         // Add the actions from the service (which willal so add the groups)
401
ISelection selection = getViewer().getSelection();
402         actionService.setContext(new ActionContext(selection));
403         actionService.fillContextMenu(manager);
404         
405         // Add any programmatic menu items
406
super.fillContextMenu(viewer, manager);
407     }
408     
409     /* (non-Javadoc)
410      * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#dispose()
411      */

412     public void dispose() {
413         TeamUI.getTeamContentProviderManager().removePropertyChangeListener(this);
414         getConfiguration().removePropertyChangeListener(this);
415         actionService.dispose();
416         super.dispose();
417     }
418     
419     /* (non-Javadoc)
420      * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#updateActionBars(org.eclipse.jface.viewers.IStructuredSelection)
421      */

422     protected void updateActionBars(IStructuredSelection selection) {
423         super.updateActionBars(selection);
424         if (!getConfiguration().getSite().isModal()) {
425             actionService.setContext(new ActionContext(selection));
426             // This is non-standard behavior that is required by the common navigator framework (see bug 122808)
427
SubActionBars subActionBars = (SubActionBars)getConfiguration().getProperty(PROP_ACTION_SERVICE_ACTION_BARS);
428             if (subActionBars == null) {
429                 subActionBars = new CommonSubActionBars(getConfiguration().getSite().getActionBars());
430                 getConfiguration().setProperty(PROP_ACTION_SERVICE_ACTION_BARS, subActionBars);
431             }
432             actionService.fillActionBars(subActionBars);
433         }
434     }
435     
436     /* (non-Javadoc)
437      * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#createContextMenuManager(java.lang.String)
438      */

439     protected MenuManager createContextMenuManager(String JavaDoc targetID) {
440         return new CommonMenuManager(targetID);
441     }
442     
443     /* (non-Javadoc)
444      * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#addContextMenuGroups(org.eclipse.jface.action.IMenuManager)
445      */

446     protected void addContextMenuGroups(IMenuManager manager) {
447         // Don't do anything. The groups will be added by the action service
448
}
449
450     public void addEmptyTreeListener(IEmptyTreeListener emptyTreeListener) {
451         this.emptyTreeListener = emptyTreeListener;
452     }
453
454     public void treeEmpty(TreeViewer viewer) {
455         if (emptyTreeListener != null)
456             emptyTreeListener.treeEmpty(viewer);
457     }
458
459     public void notEmpty(TreeViewer viewer) {
460         if (emptyTreeListener != null)
461             emptyTreeListener.notEmpty(viewer);
462     }
463
464     public void propertyChange(final PropertyChangeEvent event) {
465         if (event.getProperty().equals(ITeamContentProviderManager.PROP_ENABLED_MODEL_PROVIDERS)) {
466             enableContentProviders((CommonViewer)getViewer(), getConfiguration());
467         } else if (event.getProperty().equals(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER)) {
468             enableContentProviders((CommonViewer)getViewer(), getConfiguration());
469             final Viewer viewer = getViewer();
470             Utils.syncExec(new Runnable JavaDoc() {
471                 public void run() {
472                     Object JavaDoc viewerInput = ModelSynchronizePage.getViewerInput(getConfiguration(), (String JavaDoc)event.getNewValue());
473                     if (viewer != null && viewerInput != null) {
474                         viewer.setInput(viewerInput);
475                     }
476                 }
477             }, (StructuredViewer)viewer);
478         } else if (event.getProperty().equals(ITeamContentProviderManager.PROP_PAGE_LAYOUT)) {
479             // TODO
480
enableContentProviders((CommonViewer)getViewer(), getConfiguration());
481         }
482     }
483     
484     protected boolean handleDoubleClick(StructuredViewer viewer, DoubleClickEvent event) {
485         if (isOpenable(event.getSelection())) {
486             return true;
487         }
488         return super.handleDoubleClick(viewer, event);
489     }
490
491     private boolean isOpenable(ISelection selection) {
492         IStructuredSelection ss = (IStructuredSelection) selection;
493         Object JavaDoc object = ss.getFirstElement();
494         if (object == null)
495             return false;
496         return getParticipant().hasCompareInputFor(object);
497     }
498     
499     protected void expandToNextDiff(Object JavaDoc element) {
500         ((TreeViewer)getViewer()).expandToLevel(element, AbstractTreeViewer.ALL_LEVELS);
501     }
502
503 }
504
Popular Tags