KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > team > internal > ui > Utils


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;
12
13 import java.io.*;
14 import java.lang.reflect.InvocationTargetException JavaDoc;
15 import java.util.*;
16 import java.util.List JavaDoc;
17
18 import org.eclipse.compare.CompareConfiguration;
19 import org.eclipse.compare.structuremergeviewer.IDiffContainer;
20 import org.eclipse.compare.structuremergeviewer.IDiffElement;
21 import org.eclipse.core.resources.*;
22 import org.eclipse.core.resources.mapping.*;
23 import org.eclipse.core.runtime.*;
24 import org.eclipse.core.runtime.content.IContentType;
25 import org.eclipse.core.runtime.jobs.Job;
26 import org.eclipse.jface.action.IAction;
27 import org.eclipse.jface.dialogs.ErrorDialog;
28 import org.eclipse.jface.dialogs.MessageDialog;
29 import org.eclipse.jface.operation.IRunnableWithProgress;
30 import org.eclipse.jface.resource.ImageDescriptor;
31 import org.eclipse.jface.viewers.IStructuredSelection;
32 import org.eclipse.jface.viewers.StructuredViewer;
33 import org.eclipse.osgi.util.NLS;
34 import org.eclipse.swt.custom.BusyIndicator;
35 import org.eclipse.swt.widgets.*;
36 import org.eclipse.team.core.RepositoryProvider;
37 import org.eclipse.team.core.TeamException;
38 import org.eclipse.team.core.diff.IDiff;
39 import org.eclipse.team.core.diff.IThreeWayDiff;
40 import org.eclipse.team.core.history.IFileHistoryProvider;
41 import org.eclipse.team.core.history.IFileRevision;
42 import org.eclipse.team.core.mapping.IResourceDiff;
43 import org.eclipse.team.core.mapping.ISynchronizationScope;
44 import org.eclipse.team.core.synchronize.FastSyncInfoFilter;
45 import org.eclipse.team.core.synchronize.SyncInfo;
46 import org.eclipse.team.core.variants.IResourceVariant;
47 import org.eclipse.team.internal.core.mapping.CompoundResourceTraversal;
48 import org.eclipse.team.internal.ui.history.FileRevisionEditorInput;
49 import org.eclipse.team.internal.ui.synchronize.SyncInfoModelElement;
50 import org.eclipse.team.ui.TeamImages;
51 import org.eclipse.team.ui.TeamUI;
52 import org.eclipse.team.ui.mapping.ISynchronizationCompareAdapter;
53 import org.eclipse.team.ui.synchronize.*;
54 import org.eclipse.ui.*;
55 import org.eclipse.ui.ide.IContributorResourceAdapter2;
56 import org.eclipse.ui.ide.IDE;
57 import org.eclipse.ui.internal.ErrorEditorPart;
58 import org.eclipse.ui.progress.IWorkbenchSiteProgressService;
59
60 public class Utils {
61
62     /**
63      * The SortOperation takes a collection of objects and returns a sorted
64      * collection of these objects. Concrete instances of this class provide
65      * the criteria for the sorting of the objects based on the type of the
66      * objects.
67      */

68     static public abstract class Sorter {
69
70         /**
71          * Returns true is elementTwo is 'greater than' elementOne This is the
72          * 'ordering' method of the sort operation. Each subclass overrides this
73          * method with the particular implementation of the 'greater than'
74          * concept for the objects being sorted.
75          * @param elementOne element 1
76          * @param elementTwo element 2
77          * @return whether element 2 is greater that element 1
78          */

79         public abstract boolean compare(Object JavaDoc elementOne, Object JavaDoc elementTwo);
80
81         /**
82          * Sort the objects in sorted collection and return that collection.
83          */

84         private Object JavaDoc[] quickSort(Object JavaDoc[] sortedCollection, int left, int right) {
85             int originalLeft = left;
86             int originalRight = right;
87             Object JavaDoc mid = sortedCollection[(left + right) / 2];
88             do {
89                 while (compare(sortedCollection[left], mid))
90                     left++;
91                 while (compare(mid, sortedCollection[right]))
92                     right--;
93                 if (left <= right) {
94                     Object JavaDoc tmp = sortedCollection[left];
95                     sortedCollection[left] = sortedCollection[right];
96                     sortedCollection[right] = tmp;
97                     left++;
98                     right--;
99                 }
100             } while (left <= right);
101             if (originalLeft < right)
102                 sortedCollection = quickSort(sortedCollection, originalLeft, right);
103             if (left < originalRight)
104                 sortedCollection = quickSort(sortedCollection, left, originalRight);
105             return sortedCollection;
106         }
107
108         /**
109          * Return a new sorted collection from this unsorted collection. Sort
110          * using quick sort.
111          * @param unSortedCollection the original collection
112          * @return the sorted collection
113          */

114         public Object JavaDoc[] sort(Object JavaDoc[] unSortedCollection) {
115             int size = unSortedCollection.length;
116             Object JavaDoc[] sortedCollection = new Object JavaDoc[size];
117             //copy the array so can return a new sorted collection
118
System.arraycopy(unSortedCollection, 0, sortedCollection, 0, size);
119             if (size > 1)
120                 quickSort(sortedCollection, 0, size - 1);
121             return sortedCollection;
122         }
123     }
124
125     public static final Comparator resourceComparator = new Comparator() {
126         public boolean equals(Object JavaDoc obj) {
127             return false;
128         }
129         public int compare(Object JavaDoc o1, Object JavaDoc o2) {
130                 IResource resource0 = (IResource) o1;
131                 IResource resource1 = (IResource) o2;
132                 return resource0.getFullPath().toString().compareTo(resource1.getFullPath().toString());
133         }
134     };
135     
136     /**
137      * Shows the given errors to the user.
138      * @param shell
139      * the shell to open the error dialog in
140      * @param exception
141      * the exception containing the error
142      * @param title
143      * the title of the error dialog
144      * @param message
145      * the message for the error dialog
146      */

147     public static void handleError(Shell shell, Exception JavaDoc exception, String JavaDoc title, String JavaDoc message) {
148         IStatus status = null;
149         boolean log = false;
150         boolean dialog = false;
151         Throwable JavaDoc t = exception;
152         if (exception instanceof TeamException) {
153             status = ((TeamException) exception).getStatus();
154             log = false;
155             dialog = true;
156         } else if (exception instanceof InvocationTargetException JavaDoc) {
157             t = ((InvocationTargetException JavaDoc) exception).getTargetException();
158             if (t instanceof TeamException) {
159                 status = ((TeamException) t).getStatus();
160                 log = false;
161                 dialog = true;
162             } else if (t instanceof CoreException) {
163                 status = ((CoreException) t).getStatus();
164                 log = true;
165                 dialog = true;
166             } else if (t instanceof InterruptedException JavaDoc) {
167                 return;
168             } else {
169                 status = new Status(IStatus.ERROR, TeamUIPlugin.ID, 1, TeamUIMessages.TeamAction_internal, t);
170                 log = true;
171                 dialog = true;
172             }
173         }
174         if (status == null)
175             return;
176         if (!status.isOK()) {
177             IStatus toShow = status;
178             if (status.isMultiStatus()) {
179                 IStatus[] children = status.getChildren();
180                 if (children.length == 1) {
181                     toShow = children[0];
182                 }
183             }
184             if (title == null) {
185                 title = status.getMessage();
186             }
187             if (message == null) {
188                 message = status.getMessage();
189             }
190             if (dialog && shell != null) {
191                 ErrorDialog.openError(shell, title, message, toShow);
192             }
193             if (log || shell == null) {
194                 TeamUIPlugin.log(toShow.getSeverity(), message, t);
195             }
196         }
197     }
198
199     public static void runWithProgress(Shell parent, boolean cancelable, final IRunnableWithProgress runnable) throws InvocationTargetException JavaDoc, InterruptedException JavaDoc {
200         boolean createdShell = false;
201         try {
202             if (parent == null || parent.isDisposed()) {
203                 Display display = Display.getCurrent();
204                 if (display == null) {
205                     // cannot provide progress (not in UI thread)
206
runnable.run(new NullProgressMonitor());
207                     return;
208                 }
209                 // get the active shell or a suitable top-level shell
210
parent = display.getActiveShell();
211                 if (parent == null) {
212                     parent = new Shell(display);
213                     createdShell = true;
214                 }
215             }
216             // pop up progress dialog after a short delay
217
final Exception JavaDoc[] holder = new Exception JavaDoc[1];
218             BusyIndicator.showWhile(parent.getDisplay(), new Runnable JavaDoc() {
219
220                 public void run() {
221                     try {
222                         runnable.run(new NullProgressMonitor());
223                     } catch (InvocationTargetException JavaDoc e) {
224                         holder[0] = e;
225                     } catch (InterruptedException JavaDoc e) {
226                         holder[0] = e;
227                     }
228                 }
229             });
230             if (holder[0] != null) {
231                 if (holder[0] instanceof InvocationTargetException JavaDoc) {
232                     throw (InvocationTargetException JavaDoc) holder[0];
233                 } else {
234                     throw (InterruptedException JavaDoc) holder[0];
235                 }
236             }
237             //new TimeoutProgressMonitorDialog(parent, TIMEOUT).run(true
238
// /*fork*/, cancelable, runnable);
239
} finally {
240             if (createdShell)
241                 parent.dispose();
242         }
243     }
244
245     public static Shell getShell(IWorkbenchSite site) {
246         return getShell(site, false);
247     }
248     
249     public static Shell getShell(IWorkbenchSite site, boolean syncIfNecessary) {
250         if(site != null) {
251             Shell shell = site.getShell();
252             if (!shell.isDisposed())
253                 return shell;
254         }
255         IWorkbench workbench = TeamUIPlugin.getPlugin().getWorkbench();
256         if (workbench != null) {
257             IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
258             if (window != null) {
259                 return window.getShell();
260             }
261         }
262         // Fallback to using the display
263
Display display = Display.getCurrent();
264         if (display == null) {
265             display = Display.getDefault();
266             if (display.isDisposed()) return null;
267             if (syncIfNecessary) {
268                 final Shell[] result = new Shell[] { null };
269                 Runnable JavaDoc r = new Runnable JavaDoc() {
270                     public void run() {
271                         result[0] = new Shell(Display.getDefault());
272                     }
273                 };
274                 display.syncExec(r);
275                 return result[0];
276             }
277         }
278         if (display.isDisposed()) return null;
279         return new Shell(display);
280     }
281     /*
282      * This method is only for use by the Target Management feature (see bug
283      * 16509). @param t
284      */

285     public static void handle(final Throwable JavaDoc exception) {
286         TeamUIPlugin.getStandardDisplay().asyncExec(new Runnable JavaDoc() {
287             public void run() {
288                 IStatus error = null;
289                 Throwable JavaDoc t = exception;
290                 if (t instanceof InvocationTargetException JavaDoc) {
291                     t = ((InvocationTargetException JavaDoc) t).getTargetException();
292                 }
293                 if (t instanceof CoreException) {
294                     error = ((CoreException) t).getStatus();
295                 } else if (t instanceof TeamException) {
296                     error = ((TeamException) t).getStatus();
297                 } else {
298                     error = new Status(IStatus.ERROR, TeamUIPlugin.ID, 1, TeamUIMessages.simpleInternal, t);
299                 }
300                 Shell shell = new Shell(Display.getDefault());
301                 if (error.getSeverity() == IStatus.INFO) {
302                     MessageDialog.openInformation(shell, TeamUIMessages.information, error.getMessage());
303                 } else {
304                     ErrorDialog.openError(shell, TeamUIMessages.exception, null, error);
305                 }
306                 shell.dispose();
307                 // Let's log non-team exceptions
308
if (!(t instanceof TeamException)) {
309                     TeamUIPlugin.log(error.getSeverity(), error.getMessage(), t);
310                 }
311             }
312         });
313     }
314
315     public static Shell findShell() {
316         Display display = TeamUIPlugin.getStandardDisplay();
317         Shell activeShell = display.getActiveShell();
318         if (activeShell != null)
319             return activeShell;
320         // worst case, just create our own.
321
return new Shell(display);
322     }
323
324     public static void initAction(IAction a, String JavaDoc prefix) {
325         Utils.initAction(a, prefix, Policy.getActionBundle());
326     }
327     
328     public static void initAction(IAction a, String JavaDoc prefix, ResourceBundle bundle) {
329         Utils.initAction(a, prefix, bundle, null);
330     }
331     
332     public static void updateLabels(SyncInfo sync, CompareConfiguration config) {
333         final IResourceVariant remote = sync.getRemote();
334         final IResourceVariant base = sync.getBase();
335         String JavaDoc localContentId = sync.getLocalContentIdentifier();
336         if (localContentId != null) {
337             config.setLeftLabel(NLS.bind(TeamUIMessages.SyncInfoCompareInput_localLabelExists, new String JavaDoc[] { localContentId }));
338         } else {
339             config.setLeftLabel(TeamUIMessages.SyncInfoCompareInput_localLabel);
340         }
341         if (remote != null) {
342             config.setRightLabel(NLS.bind(TeamUIMessages.SyncInfoCompareInput_remoteLabelExists, new String JavaDoc[] { remote.getContentIdentifier() }));
343         } else {
344             config.setRightLabel(TeamUIMessages.SyncInfoCompareInput_remoteLabel);
345         }
346         if (base != null) {
347             config.setAncestorLabel(NLS.bind(TeamUIMessages.SyncInfoCompareInput_baseLabelExists, new String JavaDoc[] { base.getContentIdentifier() }));
348         } else {
349             config.setAncestorLabel(TeamUIMessages.SyncInfoCompareInput_baseLabel);
350         }
351     }
352
353     public static String JavaDoc getLocalContentId(IDiff diff) {
354         if (diff instanceof IThreeWayDiff) {
355             IThreeWayDiff twd = (IThreeWayDiff) diff;
356             diff = twd.getLocalChange();
357             if (diff == null)
358                 diff = twd.getRemoteChange();
359         }
360         if (diff instanceof IResourceDiff) {
361             IResourceDiff rd = (IResourceDiff) diff;
362             IResource resource = rd.getResource();
363             IFileHistoryProvider provider = getHistoryProvider(resource);
364             if (provider != null) {
365                 IFileRevision revision = provider.getWorkspaceFileRevision(resource);
366                 if (revision != null)
367                     return revision.getContentIdentifier();
368             }
369         }
370         return null;
371     }
372
373     public static IFileHistoryProvider getHistoryProvider(IResource resource) {
374         RepositoryProvider rp = RepositoryProvider.getProvider(resource.getProject());
375         if (rp != null)
376             return rp.getFileHistoryProvider();
377         return null;
378     }
379
380     public static IFileRevision getBase(IDiff diff) {
381         if (diff instanceof IThreeWayDiff) {
382             IThreeWayDiff twd = (IThreeWayDiff) diff;
383             IDiff remoteChange = twd.getRemoteChange();
384             if (remoteChange instanceof IResourceDiff) {
385                 IResourceDiff rd = (IResourceDiff) remoteChange;
386                 return rd.getBeforeState();
387             }
388             IDiff localChange = twd.getLocalChange();
389             if (localChange instanceof IResourceDiff) {
390                 IResourceDiff ld = (IResourceDiff) localChange;
391                 return ld.getBeforeState();
392             }
393         }
394         return null;
395     }
396
397     public static IFileRevision getRemote(IDiff diff) {
398         if (diff instanceof IResourceDiff) {
399             IResourceDiff rd = (IResourceDiff) diff;
400             return rd.getAfterState();
401         }
402         if (diff instanceof IThreeWayDiff) {
403             IThreeWayDiff twd = (IThreeWayDiff) diff;
404             IDiff remoteChange = twd.getRemoteChange();
405             if (remoteChange instanceof IResourceDiff) {
406                 IResourceDiff rd = (IResourceDiff) remoteChange;
407                 return rd.getAfterState();
408             }
409             IDiff localChange = twd.getLocalChange();
410             if (localChange instanceof IResourceDiff) {
411                 IResourceDiff ld = (IResourceDiff) localChange;
412                 return ld.getBeforeState();
413             }
414         }
415         return null;
416     }
417
418     /**
419      * Initialize the given Action from a ResourceBundle.
420      * @param a the action
421      * @param prefix the bundle key prefix
422      * @param bundle the bundle
423      * @param bindings additional input to the action label
424      */

425     public static void initAction(IAction a, String JavaDoc prefix, ResourceBundle bundle, String JavaDoc[] bindings) {
426         String JavaDoc labelKey = "label"; //$NON-NLS-1$
427
String JavaDoc tooltipKey = "tooltip"; //$NON-NLS-1$
428
String JavaDoc imageKey = "image"; //$NON-NLS-1$
429
String JavaDoc descriptionKey = "description"; //$NON-NLS-1$
430
if (prefix != null && prefix.length() > 0) {
431             labelKey = prefix + labelKey;
432             tooltipKey = prefix + tooltipKey;
433             imageKey = prefix + imageKey;
434             descriptionKey = prefix + descriptionKey;
435         }
436         String JavaDoc s = null;
437         if(bindings != null) {
438             s = NLS.bind(getString(labelKey, bundle), bindings);
439         } else {
440             s = getString(labelKey, bundle);
441         }
442         if (s != null)
443             a.setText(s);
444         s = getString(tooltipKey, bundle);
445         if (s != null)
446             a.setToolTipText(s);
447         s = getString(descriptionKey, bundle);
448         if (s != null)
449             a.setDescription(s);
450         String JavaDoc relPath = getString(imageKey, bundle);
451         if (relPath != null && !relPath.equals(imageKey) && relPath.trim().length() > 0) {
452             String JavaDoc dPath;
453             String JavaDoc ePath;
454             if (relPath.indexOf("/") >= 0) { //$NON-NLS-1$
455
String JavaDoc path = relPath.substring(1);
456                 dPath = 'd' + path;
457                 ePath = 'e' + path;
458             } else {
459                 dPath = "dlcl16/" + relPath; //$NON-NLS-1$
460
ePath = "elcl16/" + relPath; //$NON-NLS-1$
461
}
462             ImageDescriptor id = TeamImages.getImageDescriptor(dPath);
463             if (id != null)
464                 a.setDisabledImageDescriptor(id);
465             id = TeamUIPlugin.getImageDescriptor(ePath);
466             if (id != null)
467                 a.setImageDescriptor(id);
468         }
469     }
470     
471     public static String JavaDoc getString(String JavaDoc key, ResourceBundle b) {
472         try {
473             return b.getString(key);
474         } catch (MissingResourceException e) {
475             return key;
476         } catch (NullPointerException JavaDoc e) {
477             return "!" + key + "!"; //$NON-NLS-1$ //$NON-NLS-2$
478
}
479     }
480
481     public static String JavaDoc modeToString(int mode) {
482         switch (mode) {
483             case ISynchronizePageConfiguration.INCOMING_MODE :
484                 return TeamUIMessages.Utils_22;
485             case ISynchronizePageConfiguration.OUTGOING_MODE :
486                 return TeamUIMessages.Utils_23;
487             case ISynchronizePageConfiguration.BOTH_MODE :
488                 return TeamUIMessages.Utils_24;
489             case ISynchronizePageConfiguration.CONFLICTING_MODE :
490                 return TeamUIMessages.Utils_25;
491         }
492         return TeamUIMessages.Utils_26;
493     }
494
495     /**
496      * Returns the list of resources contained in the given elements.
497      * @param elements
498      * @return the list of resources contained in the given elements.
499      */

500     private static IResource[] getResources(Object JavaDoc[] elements, List JavaDoc nonResources, boolean isContributed, boolean includeMappingResources) {
501         List JavaDoc resources = new ArrayList();
502         for (int i = 0; i < elements.length; i++) {
503             Object JavaDoc element = elements[i];
504             boolean isResource = false;
505             if (element instanceof IResource) {
506                 resources.add(element);
507                 isResource = true;
508             } else if (element instanceof ISynchronizeModelElement){
509                 IResource resource = ((ISynchronizeModelElement) element).getResource();
510                 if (resource != null) {
511                     resources.add(resource);
512                     isResource = true;
513                 }
514             } else if (element instanceof ResourceMapping) {
515                 if (includeMappingResources) {
516                     isResource = true;
517                     getResources((ResourceMapping)element, resources);
518                 }
519             } else if (element != null) {
520                 Object JavaDoc adapted;
521                 if (isContributed) {
522                     adapted = getResource(element);
523                 } else {
524                     adapted = getAdapter(element, IResource.class);
525                 }
526                 if (adapted instanceof IResource) {
527                     IResource resource = (IResource) adapted;
528                     isResource = true;
529                     if (resource.getType() != IResource.ROOT) {
530                         resources.add(resource);
531                     }
532                 } else {
533                     if (isContributed) {
534                         adapted = getResourceMapping(element);
535                     } else {
536                         adapted = getAdapter(element, ResourceMapping.class);
537                     }
538                     if (adapted instanceof ResourceMapping && includeMappingResources) {
539                         isResource = true;
540                         getResources((ResourceMapping) adapted, resources);
541                     }
542                 }
543             }
544             if (!isResource) {
545                 if(nonResources != null)
546                     nonResources.add(element);
547             }
548         }
549         return (IResource[]) resources.toArray(new IResource[resources.size()]);
550     }
551
552     private static void getResources(ResourceMapping element, List JavaDoc resources) {
553         try {
554             ResourceTraversal[] traversals = element.getTraversals(ResourceMappingContext.LOCAL_CONTEXT, null);
555             for (int k = 0; k < traversals.length; k++) {
556                 ResourceTraversal traversal = traversals[k];
557                 IResource[] resourceArray = traversal.getResources();
558                 for (int j = 0; j < resourceArray.length; j++) {
559                     IResource resource = resourceArray[j];
560                     resources.add(resource);
561                 }
562             }
563         } catch (CoreException e) {
564             TeamUIPlugin.log(new Status(IStatus.ERROR, TeamUIPlugin.ID, 0, "Error traversing resource mapping", e)); //$NON-NLS-1$
565
}
566     }
567     
568     public static Object JavaDoc[] getNonResources(Object JavaDoc[] elements) {
569         List JavaDoc nonResources = new ArrayList();
570         getResources(elements, nonResources, false, false);
571         return nonResources.toArray();
572     }
573     
574     public static IResource[] getResources(Object JavaDoc[] element) {
575         return getResources(element, null, false /* isContributed */, false /* includeMappingResources */);
576     }
577     
578     public static IResource[] getContributedResources(Object JavaDoc[] elements) {
579         return getResources(elements, null, true /* isContributed */, true /* isIncudeMappings */);
580     }
581     
582     public static Object JavaDoc getAdapter(Object JavaDoc element, Class JavaDoc adapterType, boolean load) {
583         if (adapterType.isInstance(element))
584             return element;
585         if (element instanceof IAdaptable) {
586             Object JavaDoc adapted = ((IAdaptable) element).getAdapter(adapterType);
587             if (adapterType.isInstance(adapted))
588                 return adapted;
589         }
590         if (load) {
591             Object JavaDoc adapted = Platform.getAdapterManager().loadAdapter(element, adapterType.getName());
592             if (adapterType.isInstance(adapted))
593                 return adapted;
594         } else {
595             Object JavaDoc adapted = Platform.getAdapterManager().getAdapter(element, adapterType);
596             if (adapterType.isInstance(adapted))
597                 return adapted;
598         }
599         return null;
600     }
601     
602     public static Object JavaDoc getAdapter(Object JavaDoc element, Class JavaDoc adapterType) {
603         return getAdapter(element, adapterType, false);
604     }
605     
606     /**
607      * Return whether any sync nodes in the given selection or their
608      * descendants match the given filter.
609      * @param selection a selection
610      * @param filter a sync info filter
611      * @return whether any sync nodes in the given selection or their
612      * descendants match the given filter
613      */

614     public static boolean hasMatchingDescendant(IStructuredSelection selection, FastSyncInfoFilter filter) {
615         for (Iterator iter = selection.iterator(); iter.hasNext();) {
616             Object JavaDoc o = iter.next();
617             if (o instanceof ISynchronizeModelElement) {
618                 if (hasMatchingDescendant((ISynchronizeModelElement)o, filter)) {
619                     return true;
620                 }
621             }
622         }
623         return false;
624     }
625     
626     private static boolean hasMatchingDescendant(ISynchronizeModelElement element, FastSyncInfoFilter filter) {
627         if (element.getKind() != SyncInfo.IN_SYNC && element instanceof SyncInfoModelElement) {
628             SyncInfo info = ((SyncInfoModelElement) element).getSyncInfo();
629             if (info != null && filter.select(info)) {
630                 return true;
631             }
632         }
633         IDiffElement[] children = element.getChildren();
634         for (int i = 0; i < children.length; i++) {
635             IDiffElement child = children[i];
636             if (child instanceof ISynchronizeModelElement) {
637                 if (hasMatchingDescendant((ISynchronizeModelElement)child, filter)) {
638                     return true;
639                 }
640             }
641         }
642         return false;
643     }
644
645     /**
646      * This method returns all out-of-sync SyncInfos that are in the current
647      * selection.
648      * @param selected the selected objects
649      *
650      * @return the list of selected sync infos
651      */

652     public static IDiffElement[] getDiffNodes(Object JavaDoc[] selected) {
653         Set result = new HashSet();
654         for (int i = 0; i < selected.length; i++) {
655             Object JavaDoc object = selected[i];
656             if(object instanceof IDiffElement) {
657                 collectAllNodes((IDiffElement)object, result);
658             }
659         }
660         return (IDiffElement[]) result.toArray(new IDiffElement[result.size()]);
661     }
662     
663     private static void collectAllNodes(IDiffElement element, Set nodes) {
664         if(element.getKind() != SyncInfo.IN_SYNC) {
665             nodes.add(element);
666         }
667         if(element instanceof IDiffContainer) {
668             IDiffElement[] children = ((IDiffContainer)element).getChildren();
669             for (int i = 0; i < children.length; i++) {
670                 collectAllNodes(children[i], nodes);
671             }
672         }
673     }
674     
675     public static void schedule(Job job, IWorkbenchSite site) {
676         if (site != null) {
677             IWorkbenchSiteProgressService siteProgress = (IWorkbenchSiteProgressService) site.getAdapter(IWorkbenchSiteProgressService.class);
678             if (siteProgress != null) {
679                 siteProgress.schedule(job, 0, true /* use half-busy cursor */);
680                 return;
681             }
682         }
683         job.schedule();
684     }
685     
686     public static byte[] readBytes(InputStream in) {
687         ByteArrayOutputStream bos= new ByteArrayOutputStream();
688         try {
689             while (true) {
690                 int c= in.read();
691                 if (c == -1)
692                     break;
693                 bos.write(c);
694             }
695                     
696         } catch (IOException ex) {
697             return null;
698         
699         } finally {
700             if (in != null) {
701                 try {
702                     in.close();
703                 } catch (IOException x) {
704                     // silently ignored
705
}
706             }
707             try {
708                 bos.close();
709             } catch (IOException x) {
710                 // silently ignored
711
}
712         }
713         return bos.toByteArray();
714     }
715     
716     public static boolean equalObject(Object JavaDoc o1, Object JavaDoc o2) {
717         if (o1 == null && o2 == null) return true;
718         if (o1 == null || o2 == null) return false;
719         return o1.equals(o2);
720     }
721
722     public static String JavaDoc getKey(String JavaDoc id, String JavaDoc secondaryId) {
723         return secondaryId == null ? id : id + '/' + secondaryId;
724     }
725     
726     public static String JavaDoc convertSelection(IResource[] resources) {
727         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
728         for (int i = 0; i < resources.length; i++) {
729             IResource resource = resources[i];
730             if(i > 0) buffer.append(", "); //$NON-NLS-1$
731
buffer.append(resource.getFullPath());
732         }
733         return buffer.toString();
734     }
735     
736     /**
737      * Shorten the given text <code>t</code> so that its length
738      * doesn't exceed the given width. This implementation
739      * replaces characters in the center of the original string with an
740      * ellipsis ("...").
741      * @param maxWidth the maximum length for the text
742      * @param textValue the text to be shortened
743      * @return the shortened text
744      */

745     public static String JavaDoc shortenText(int maxWidth, String JavaDoc textValue) {
746         int length = textValue.length();
747         if (length < maxWidth)
748             return textValue;
749         String JavaDoc ellipsis = "..."; //$NON-NLS-1$
750
int subStrLen = (maxWidth - ellipsis.length()) / 2;
751         int addtl = (maxWidth - ellipsis.length()) % 2;
752
753         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
754         sb.append(textValue.substring(0, subStrLen));
755         sb.append(ellipsis);
756         sb.append(textValue.substring(length - subStrLen - addtl));
757         return sb.toString();
758     }
759     
760     public static String JavaDoc getTypeName(ISynchronizeParticipant participant) {
761         ISynchronizeManager manager = TeamUI.getSynchronizeManager();
762         return manager.getParticipantDescriptor(participant.getId()).getName();
763     }
764
765     /**
766      * The viewer will only be updated if the viewer is not null, the control is not disposed, and
767      * this code is being run from the UI thread.
768      * @param viewer the viewer to be updated
769      * @return whether it is safe to update the viewer
770      */

771     public static boolean canUpdateViewer(StructuredViewer viewer) {
772         if(viewer == null || viewer.getControl().isDisposed()) return false;
773         Display display = viewer.getControl().getDisplay();
774         if (display == null) return false;
775         if (display.getThread() != Thread.currentThread ()) return false;
776         return true;
777     }
778     
779     public static void asyncExec(final Runnable JavaDoc r, StructuredViewer v) {
780         if(v == null) return;
781         final Control ctrl = v.getControl();
782         if (ctrl != null && !ctrl.isDisposed()) {
783             ctrl.getDisplay().asyncExec(new Runnable JavaDoc() {
784                 public void run() {
785                     if (!ctrl.isDisposed()) {
786                         BusyIndicator.showWhile(ctrl.getDisplay(), r);
787                     }
788                 }
789             });
790         }
791     }
792
793     public static void syncExec(final Runnable JavaDoc r, StructuredViewer v) {
794         if(v == null) return;
795         final Control ctrl = v.getControl();
796         syncExec(r, ctrl);
797     }
798
799     public static void syncExec(final Runnable JavaDoc r, final Control ctrl) {
800         if (ctrl != null && !ctrl.isDisposed()) {
801             ctrl.getDisplay().syncExec(new Runnable JavaDoc() {
802                 public void run() {
803                     if (!ctrl.isDisposed()) {
804                         BusyIndicator.showWhile(ctrl.getDisplay(), r);
805                     }
806                 }
807             });
808         }
809     }
810     
811     public static void asyncExec(final Runnable JavaDoc r, final Control ctrl) {
812         if (ctrl != null && !ctrl.isDisposed()) {
813             ctrl.getDisplay().asyncExec(new Runnable JavaDoc() {
814                 public void run() {
815                     if (!ctrl.isDisposed()) {
816                         BusyIndicator.showWhile(ctrl.getDisplay(), r);
817                     }
818                 }
819             });
820         }
821     }
822
823     public static SyncInfo getSyncInfo(ISynchronizeModelElement node) {
824         if (node instanceof IAdaptable) {
825             return (SyncInfo)((IAdaptable)node).getAdapter(SyncInfo.class);
826         }
827         return null;
828     }
829
830     public static ISynchronizationCompareAdapter getCompareAdapter(Object JavaDoc element) {
831         ModelProvider provider = getModelProvider(element);
832         if (provider != null) {
833             Object JavaDoc o = provider.getAdapter(ISynchronizationCompareAdapter.class);
834             if (o instanceof ISynchronizationCompareAdapter) {
835                 return (ISynchronizationCompareAdapter) o;
836             }
837         }
838         return null;
839     }
840
841     public static ModelProvider getModelProvider(Object JavaDoc o) {
842         if (o instanceof ModelProvider) {
843             return (ModelProvider) o;
844         }
845         ResourceMapping mapping = getResourceMapping(o);
846         if (mapping != null)
847             return mapping.getModelProvider();
848         return null;
849     }
850     
851     public static IResource getResource(Object JavaDoc o) {
852         IResource resource = null;
853         if (o instanceof IResource) {
854             resource = (IResource) o;
855         } else if (o instanceof IAdaptable) {
856             IAdaptable adaptable = (IAdaptable) o;
857             resource = (IResource)adaptable.getAdapter(IResource.class);
858             if (resource == null) {
859                 IContributorResourceAdapter adapter = (IContributorResourceAdapter)adaptable.getAdapter(IContributorResourceAdapter.class);
860                 if (adapter != null)
861                     resource = adapter.getAdaptedResource(adaptable);
862             }
863         }
864         return resource;
865     }
866     
867     
868     public static ResourceMapping getResourceMapping(Object JavaDoc o) {
869         if (o instanceof ResourceMapping) {
870             return (ResourceMapping) o;
871         }
872         if (o instanceof IAdaptable) {
873             IAdaptable adaptable = (IAdaptable) o;
874             Object JavaDoc adapted = adaptable.getAdapter(ResourceMapping.class);
875             if (adapted instanceof ResourceMapping) {
876                 return(ResourceMapping) adapted;
877             }
878             adapted = adaptable.getAdapter(IContributorResourceAdapter.class);
879             if (adapted instanceof IContributorResourceAdapter2) {
880                 IContributorResourceAdapter2 cra = (IContributorResourceAdapter2) adapted;
881                 return cra.getAdaptedResourceMapping(adaptable);
882             }
883         } else {
884             Object JavaDoc adapted = Platform.getAdapterManager().getAdapter(o, ResourceMapping.class);
885             if (adapted instanceof ResourceMapping) {
886                 return(ResourceMapping) adapted;
887             }
888         }
889         return null;
890     }
891
892     public static ResourceMapping[] getResourceMappings(Object JavaDoc[] objects) {
893         List JavaDoc result = new ArrayList();
894         for (int i = 0; i < objects.length; i++) {
895             Object JavaDoc object = objects[i];
896             ResourceMapping mapping = getResourceMapping(object);
897             if (mapping != null)
898                 result.add(mapping);
899         }
900         return (ResourceMapping[]) result.toArray(new ResourceMapping[result.size()]);
901     }
902
903     public static String JavaDoc getLabel(ResourceMapping mapping) {
904         ModelProvider provider = mapping.getModelProvider();
905         ISynchronizationCompareAdapter adapter = getCompareAdapter(provider);
906         if (adapter == null)
907             return ""; //$NON-NLS-1$
908
String JavaDoc pathString = adapter.getPathString(mapping);
909         if (pathString == null || pathString.length() == 0)
910             return adapter.getName(mapping);
911         return pathString;
912     }
913     
914     public static String JavaDoc getLabel(ModelProvider provider) {
915         ResourceMapping mapping = Utils.getResourceMapping(provider);
916         if (mapping != null) {
917             String JavaDoc base = Utils.getLabel(mapping);
918             if (base != null && base.length() > 0)
919                 return base;
920         }
921         return provider.getDescriptor().getLabel();
922     }
923
924     public static String JavaDoc getScopeDescription(ISynchronizationScope scope) {
925         ResourceMapping[] mappings = scope.getInputMappings();
926         if (mappings.length == 1) {
927             String JavaDoc label = getLabel(mappings[0]);
928             if (label == null)
929                 return TeamUIMessages.Utils_19;
930             else
931                 return label;
932         }
933         String JavaDoc desc = convertSelection(mappings);
934         if (desc.length() > 0)
935             return shortenText(30, desc);
936         return NLS.bind(TeamUIMessages.Utils_18, new Integer JavaDoc(mappings.length));
937     }
938     
939     public static String JavaDoc convertSelection(ResourceMapping[] mappings) {
940         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
941         boolean hadOne = false;
942         for (int i = 0; i < mappings.length; i++) {
943             ResourceMapping resourceMapping = mappings[i];
944             String JavaDoc label = getLabel(resourceMapping);
945             if (label != null) {
946                 if(hadOne) buffer.append(", "); //$NON-NLS-1$
947
hadOne = true;
948                 buffer.append(label);
949             }
950         }
951         return buffer.toString();
952     }
953
954     public static ResourceTraversal[] getTraversals(Object JavaDoc[] elements) throws CoreException {
955         CompoundResourceTraversal traversal = new CompoundResourceTraversal();
956         for (int i = 0; i < elements.length; i++) {
957             Object JavaDoc object = elements[i];
958             ResourceMapping mapping = getResourceMapping(object);
959             if (mapping != null) {
960                 traversal.addTraversals(mapping.getTraversals(ResourceMappingContext.LOCAL_CONTEXT, null));
961             }
962         }
963         return traversal.asTraversals();
964     }
965
966     public static IEditorPart openEditor(IWorkbenchPage page, IFileRevision revision, IProgressMonitor monitor) throws CoreException {
967         IStorage file = revision.getStorage(monitor);
968         if (file instanceof IFile) {
969             //if this is the current workspace file, open it
970
return IDE.openEditor(page, (IFile) file);
971         } else {
972             FileRevisionEditorInput fileRevEditorInput = FileRevisionEditorInput.createEditorInputFor(revision, monitor);
973             IEditorPart part = findEditor(page, fileRevEditorInput);
974             if (part == null)
975                 part = openEditor(page, fileRevEditorInput);
976             return part;
977         }
978     }
979     
980     public static IEditorPart openEditor(IWorkbenchPage page, FileRevisionEditorInput editorInput) throws PartInitException {
981         String JavaDoc id = getEditorId(editorInput);
982         try {
983             IEditorPart part = page.openEditor(editorInput, id);
984             if (part instanceof ErrorEditorPart) {
985                 page.closeEditor(part, false);
986                 part = null;
987             }
988             if (part == null) {
989                 throw new PartInitException(NLS.bind(TeamUIMessages.Utils_17, id));
990             }
991             return part;
992         } catch (PartInitException e) {
993             if (id.equals("org.eclipse.ui.DefaultTextEditor")) { //$NON-NLS-1$
994
throw e;
995             } else {
996                 return page.openEditor(editorInput,"org.eclipse.ui.DefaultTextEditor"); //$NON-NLS-1$
997
}
998         }
999     }
1000
1001    private static String JavaDoc getEditorId(FileRevisionEditorInput editorInput) {
1002        String JavaDoc id = getEditorId(editorInput.getFileRevision().getName(), getContentType(editorInput));
1003        return id;
1004    }
1005
1006    private static IContentType getContentType(FileRevisionEditorInput editorInput) {
1007        IContentType type = null;
1008        try {
1009            InputStream contents = editorInput.getStorage().getContents();
1010            try {
1011                type = getContentType(editorInput.getFileRevision().getName(), contents);
1012            } finally {
1013                try {
1014                    contents.close();
1015                } catch (IOException e) {
1016                    // ignore
1017
}
1018            }
1019        } catch (CoreException e) {
1020            TeamUIPlugin.log(IStatus.ERROR, NLS.bind("An error occurred reading the contents of file {0}", new String JavaDoc[] { editorInput.getName() }), e); //$NON-NLS-1$
1021
}
1022        return type;
1023    }
1024    
1025    private static IContentType getContentType(String JavaDoc fileName, InputStream contents) {
1026        IContentType type = null;
1027        if (contents != null) {
1028            try {
1029                type = Platform.getContentTypeManager().findContentTypeFor(contents, fileName);
1030            } catch (IOException e) {
1031                TeamUIPlugin.log(IStatus.ERROR, NLS.bind("An error occurred reading the contents of file {0}", fileName), e); //$NON-NLS-1$
1032
}
1033        }
1034        if (type == null) {
1035            type = Platform.getContentTypeManager().findContentTypeFor(fileName);
1036        }
1037        return type;
1038    }
1039
1040    private static String JavaDoc getEditorId(String JavaDoc fileName, IContentType type) {
1041        IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry();
1042        IEditorDescriptor descriptor = registry.getDefaultEditor(fileName, type);
1043        String JavaDoc id;
1044        if (descriptor == null || descriptor.isOpenExternal()) {
1045            id = "org.eclipse.ui.DefaultTextEditor"; //$NON-NLS-1$
1046
} else {
1047            id = descriptor.getId();
1048        }
1049        return id;
1050    }
1051    
1052    private static IEditorPart findEditor(IWorkbenchPage page, FileRevisionEditorInput input) {
1053        IEditorReference[] editorRefs = page.getEditorReferences();
1054        for (int i = 0; i < editorRefs.length; i++) {
1055            IEditorPart part = editorRefs[i].getEditor(false);
1056            if(part != null
1057               && part.getEditorInput() instanceof FileRevisionEditorInput) {
1058                IFileRevision inputRevision = (IFileRevision) input.getAdapter(IFileRevision.class);
1059                IFileRevision editorRevision = (IFileRevision) part.getEditorInput().getAdapter(IFileRevision.class);
1060                
1061                if (inputRevision.equals(editorRevision)){
1062                    //make the editor that already contains the revision current
1063
page.activate(part);
1064                    return part;
1065                }
1066            }
1067        }
1068        return null;
1069    }
1070
1071}
1072
Popular Tags