KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > compare > internal > Utilities


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.compare.internal;
12
13 import java.io.*;
14 import java.util.*;
15 import java.util.List JavaDoc;
16
17 import org.eclipse.compare.*;
18 import org.eclipse.compare.contentmergeviewer.IDocumentRange;
19 import org.eclipse.compare.patch.IHunk;
20 import org.eclipse.compare.structuremergeviewer.DiffNode;
21 import org.eclipse.compare.structuremergeviewer.ICompareInput;
22 import org.eclipse.core.resources.*;
23 import org.eclipse.core.resources.mapping.*;
24 import org.eclipse.core.runtime.*;
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.resource.ImageDescriptor;
29 import org.eclipse.jface.text.IDocument;
30 import org.eclipse.jface.util.IPropertyChangeListener;
31 import org.eclipse.jface.util.PropertyChangeEvent;
32 import org.eclipse.jface.viewers.ISelection;
33 import org.eclipse.jface.viewers.IStructuredSelection;
34 import org.eclipse.swt.custom.BusyIndicator;
35 import org.eclipse.swt.widgets.*;
36 import org.eclipse.ui.*;
37 import org.eclipse.ui.progress.IWorkbenchSiteProgressService;
38 import org.eclipse.ui.texteditor.IDocumentProvider;
39
40 import com.ibm.icu.text.MessageFormat;
41
42 /**
43  * Convenience and utility methods.
44  */

45 public class Utilities {
46     
47     private static final IPath ICONS_PATH= new Path("$nl$/icons/full/"); //$NON-NLS-1$
48

49     public static IWorkbenchPartSite findSite(Control c) {
50         while (c != null && !c.isDisposed()) {
51             Object JavaDoc data= c.getData();
52             if (data instanceof IWorkbenchPart)
53                 return ((IWorkbenchPart)data).getSite();
54             c= c.getParent();
55         }
56         return null;
57     }
58
59     public static IActionBars findActionBars(Control c) {
60         while (c != null && !c.isDisposed()) {
61             Object JavaDoc data= c.getData();
62             if (data instanceof CompareEditor)
63                 return ((CompareEditor)data).getActionBars();
64                 
65             // PR 1GDVZV7: ITPVCM:WIN98 - CTRL + C does not work in Java source compare
66
if (data instanceof IViewPart)
67                 return ((IViewPart)data).getViewSite().getActionBars();
68             // end PR 1GDVZV7
69

70             c= c.getParent();
71         }
72         return null;
73     }
74
75     public static void setEnableComposite(Composite composite, boolean enable) {
76         Control[] children= composite.getChildren();
77         for (int i= 0; i < children.length; i++)
78             children[i].setEnabled(enable);
79     }
80
81     public static boolean getBoolean(CompareConfiguration cc, String JavaDoc key, boolean dflt) {
82         if (cc != null) {
83             Object JavaDoc value= cc.getProperty(key);
84             if (value instanceof Boolean JavaDoc)
85                 return ((Boolean JavaDoc) value).booleanValue();
86         }
87         return dflt;
88     }
89     
90     public static void firePropertyChange(ListenerList listenerList, Object JavaDoc source, String JavaDoc property, Object JavaDoc old, Object JavaDoc newValue) {
91         PropertyChangeEvent event= new PropertyChangeEvent(source, property, old, newValue);
92         firePropertyChange(listenerList, event);
93     }
94     
95     public static void firePropertyChange(final ListenerList listenerList, final PropertyChangeEvent event) {
96         if (listenerList == null || listenerList.isEmpty())
97             return;
98         // Legacy listeners may expect to get notified in the UI thread
99
Runnable JavaDoc runnable = new Runnable JavaDoc() {
100             public void run() {
101                 if (listenerList != null) {
102                     Object JavaDoc[] listeners= listenerList.getListeners();
103                     for (int i= 0; i < listeners.length; i++) {
104                         final IPropertyChangeListener listener= (IPropertyChangeListener) listeners[i];
105                         SafeRunner.run(new ISafeRunnable() {
106                             public void run() throws Exception JavaDoc {
107                                 listener.propertyChange(event);
108                             }
109                             public void handleException(Throwable JavaDoc exception) {
110                                 // Logged by SafeRunner
111
}
112                         });
113                     }
114                 }
115             }
116         };
117         if (Display.getCurrent() == null) {
118             Display.getDefault().syncExec(runnable);
119         } else {
120             runnable.run();
121         }
122     }
123
124     public static boolean okToUse(Widget widget) {
125         return widget != null && !widget.isDisposed();
126     }
127     
128     private static ArrayList internalGetResources(ISelection selection, Class JavaDoc type) {
129         ArrayList tmp= new ArrayList();
130         if (selection instanceof IStructuredSelection) {
131             Object JavaDoc[] s= ((IStructuredSelection)selection).toArray();
132                 
133             for (int i= 0; i < s.length; i++) {
134                 IResource resource= null;
135                 Object JavaDoc o= s[i];
136                 if (type.isInstance(o)) {
137                     resource= (IResource) o;
138                         
139                 } else if (o instanceof ResourceMapping) {
140                     try {
141                         ResourceTraversal[] travs= ((ResourceMapping)o).getTraversals(ResourceMappingContext.LOCAL_CONTEXT, null);
142                         if (travs != null) {
143                             for (int k= 0; k < travs.length; k++) {
144                                 IResource[] resources= travs[k].getResources();
145                                 for (int j= 0; j < resources.length; j++) {
146                                     if (type.isInstance(resources[j]) && resources[j].isAccessible())
147                                         tmp.add(resources[j]);
148                                 }
149                             }
150                         }
151                     } catch (CoreException ex) {
152                         CompareUIPlugin.log(ex);
153                     }
154                 } else if (o instanceof IAdaptable) {
155                     IAdaptable a= (IAdaptable) o;
156                     Object JavaDoc adapter= a.getAdapter(IResource.class);
157                     if (type.isInstance(adapter))
158                         resource= (IResource) adapter;
159                 }
160                 
161                 if (resource != null && resource.isAccessible())
162                     tmp.add(resource);
163             }
164         }
165         return tmp;
166     }
167
168     
169     /*
170      * Convenience method: extract all accessible <code>IResources</code> from given selection.
171      * Never returns null.
172      */

173     public static IResource[] getResources(ISelection selection) {
174         ArrayList tmp= internalGetResources(selection, IResource.class);
175         return (IResource[]) tmp.toArray(new IResource[tmp.size()]);
176     }
177     
178     /*
179      * Convenience method: extract all accessible <code>IFiles</code> from given selection.
180      * Never returns null.
181      */

182     public static IFile[] getFiles(ISelection selection) {
183         ArrayList tmp= internalGetResources(selection, IFile.class);
184         return (IFile[]) tmp.toArray(new IFile[tmp.size()]);
185     }
186
187     public static byte[] readBytes(InputStream in) {
188         ByteArrayOutputStream bos= new ByteArrayOutputStream();
189         try {
190             while (true) {
191                 int c= in.read();
192                 if (c == -1)
193                     break;
194                 bos.write(c);
195             }
196                     
197         } catch (IOException ex) {
198             return null;
199         
200         } finally {
201             Utilities.close(in);
202             try {
203                 bos.close();
204             } catch (IOException x) {
205                 // silently ignored
206
}
207         }
208         
209         return bos.toByteArray();
210     }
211
212     public static IPath getIconPath(Display display) {
213         return ICONS_PATH;
214     }
215     
216     /*
217      * Initialize the given Action from a ResourceBundle.
218      */

219     public static void initAction(IAction a, ResourceBundle bundle, String JavaDoc prefix) {
220         
221         String JavaDoc labelKey= "label"; //$NON-NLS-1$
222
String JavaDoc tooltipKey= "tooltip"; //$NON-NLS-1$
223
String JavaDoc imageKey= "image"; //$NON-NLS-1$
224
String JavaDoc descriptionKey= "description"; //$NON-NLS-1$
225

226         if (prefix != null && prefix.length() > 0) {
227             labelKey= prefix + labelKey;
228             tooltipKey= prefix + tooltipKey;
229             imageKey= prefix + imageKey;
230             descriptionKey= prefix + descriptionKey;
231         }
232         
233         a.setText(getString(bundle, labelKey, labelKey));
234         a.setToolTipText(getString(bundle, tooltipKey, null));
235         a.setDescription(getString(bundle, descriptionKey, null));
236         
237         String JavaDoc relPath= getString(bundle, imageKey, null);
238         if (relPath != null && relPath.trim().length() > 0) {
239             
240             String JavaDoc dPath;
241             String JavaDoc ePath;
242             
243             if (relPath.indexOf("/") >= 0) { //$NON-NLS-1$
244
String JavaDoc path= relPath.substring(1);
245                 dPath= 'd' + path;
246                 ePath= 'e' + path;
247             } else {
248                 dPath= "dlcl16/" + relPath; //$NON-NLS-1$
249
ePath= "elcl16/" + relPath; //$NON-NLS-1$
250
}
251             
252             ImageDescriptor id= CompareUIPlugin.getImageDescriptor(dPath); // we set the disabled image first (see PR 1GDDE87)
253
if (id != null)
254                 a.setDisabledImageDescriptor(id);
255             id= CompareUIPlugin.getImageDescriptor(ePath);
256             if (id != null) {
257                 a.setImageDescriptor(id);
258                 a.setHoverImageDescriptor(id);
259             }
260         }
261     }
262     
263     public static void initToggleAction(IAction a, ResourceBundle bundle, String JavaDoc prefix, boolean checked) {
264
265         String JavaDoc tooltip= null;
266         if (checked)
267             tooltip= getString(bundle, prefix + "tooltip.checked", null); //$NON-NLS-1$
268
else
269             tooltip= getString(bundle, prefix + "tooltip.unchecked", null); //$NON-NLS-1$
270
if (tooltip == null)
271             tooltip= getString(bundle, prefix + "tooltip", null); //$NON-NLS-1$
272

273         if (tooltip != null)
274             a.setToolTipText(tooltip);
275             
276         String JavaDoc description= null;
277         if (checked)
278             description= getString(bundle, prefix + "description.checked", null); //$NON-NLS-1$
279
else
280             description= getString(bundle, prefix + "description.unchecked", null); //$NON-NLS-1$
281
if (description == null)
282             description= getString(bundle, prefix + "description", null); //$NON-NLS-1$
283

284         if (description != null)
285             a.setDescription(description);
286             
287     }
288
289     public static String JavaDoc getString(ResourceBundle bundle, String JavaDoc key, String JavaDoc dfltValue) {
290         
291         if (bundle != null) {
292             try {
293                 return bundle.getString(key);
294             } catch (MissingResourceException x) {
295                 // fall through
296
}
297         }
298         return dfltValue;
299     }
300     
301     public static String JavaDoc getFormattedString(ResourceBundle bundle, String JavaDoc key, String JavaDoc arg) {
302         
303         if (bundle != null) {
304             try {
305                 return MessageFormat.format(bundle.getString(key), new String JavaDoc[] { arg });
306             } catch (MissingResourceException x) {
307                 CompareUIPlugin.log(x);
308             }
309         }
310         return "!" + key + "!"; //$NON-NLS-2$ //$NON-NLS-1$
311
}
312     
313     public static String JavaDoc getString(String JavaDoc key) {
314         try {
315             return CompareUI.getResourceBundle().getString(key);
316         } catch (MissingResourceException e) {
317             return "!" + key + "!"; //$NON-NLS-2$ //$NON-NLS-1$
318
}
319     }
320     
321     public static String JavaDoc getFormattedString(String JavaDoc key, String JavaDoc arg) {
322         try {
323             return MessageFormat.format(CompareUI.getResourceBundle().getString(key), new String JavaDoc[] { arg });
324         } catch (MissingResourceException e) {
325             return "!" + key + "!"; //$NON-NLS-2$ //$NON-NLS-1$
326
}
327     }
328
329     public static String JavaDoc getFormattedString(String JavaDoc key, String JavaDoc arg0, String JavaDoc arg1) {
330         try {
331             return MessageFormat.format(CompareUI.getResourceBundle().getString(key), new String JavaDoc[] { arg0, arg1 });
332         } catch (MissingResourceException e) {
333             return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$
334
}
335     }
336
337     public static String JavaDoc getString(ResourceBundle bundle, String JavaDoc key) {
338         return getString(bundle, key, key);
339     }
340     
341     public static int getInteger(ResourceBundle bundle, String JavaDoc key, int dfltValue) {
342         
343         if (bundle != null) {
344             try {
345                 String JavaDoc s= bundle.getString(key);
346                 if (s != null)
347                     return Integer.parseInt(s);
348             } catch (NumberFormatException JavaDoc x) {
349                 CompareUIPlugin.log(x);
350             } catch (MissingResourceException x) {
351                 // silently ignore Exception
352
}
353         }
354         return dfltValue;
355     }
356
357     /**
358      * Answers <code>true</code> if the given selection contains resources that don't
359      * have overlapping paths and <code>false</code> otherwise.
360      */

361     /*
362     public static boolean isSelectionNonOverlapping() throws TeamException {
363         IResource[] resources = getSelectedResources();
364         // allow operation for non-overlapping resource selections
365         if(resources.length>0) {
366             List validPaths = new ArrayList(2);
367             for (int i = 0; i < resources.length; i++) {
368                 IResource resource = resources[i];
369                 
370                 // only allow cvs resources to be selected
371                 if(RepositoryProvider.getProvider(resource.getProject(), CVSProviderPlugin.getTypeId()) == null) {
372                     return false;
373                 }
374                 
375                 // check if this resource overlaps other selections
376                 IPath resourceFullPath = resource.getFullPath();
377                 if(!validPaths.isEmpty()) {
378                     for (Iterator it = validPaths.iterator(); it.hasNext();) {
379                         IPath path = (IPath) it.next();
380                         if(path.isPrefixOf(resourceFullPath) ||
381                            resourceFullPath.isPrefixOf(path)) {
382                             return false;
383                         }
384                     }
385                 }
386                 validPaths.add(resourceFullPath);
387                 
388                 // ensure that resources are managed
389                 ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(resource);
390                 if(cvsResource.isFolder()) {
391                     if( ! ((ICVSFolder)cvsResource).isCVSFolder()) return false;
392                 } else {
393                     if( ! cvsResource.isManaged()) return false;
394                 }
395             }
396             return true;
397         }
398         return false;
399     }
400     */

401     
402     /* validate edit utilities */
403     
404     /**
405      * Status constant indicating that an validateEdit call has changed the
406      * content of a file on disk.
407      */

408     private static final int VALIDATE_EDIT_PROBLEM= 10004;
409     
410     /**
411      * Constant used to indicate that tests are being run.
412      */

413     public static boolean RUNNING_TESTS = false;
414
415     /**
416      * Constant used while testing the indicate that changes should be flushed
417      * when the compare input changes and a viewer is dirty.
418      */

419     public static boolean TESTING_FLUSH_ON_COMPARE_INPUT_CHANGE = false;
420     
421     /*
422      * Makes the given resources committable. Committable means that all
423      * resources are writeable and that the content of the resources hasn't
424      * changed by calling <code>validateEdit</code> for a given file on
425      * <tt>IWorkspace</tt>.
426      *
427      * @param resources the resources to be checked
428      * @param shell the Shell passed to <code>validateEdit</code> as a context
429      * @return returns <code>true</code> if all resources are committable, <code>false</code> otherwise
430      *
431      * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object)
432      */

433     public static boolean validateResource(IResource resource, Shell shell, String JavaDoc title) {
434         return validateResources(new IResource[] { resource }, shell, title);
435     }
436     
437     /*
438      * Makes the given resources committable. Committable means that all
439      * resources are writeable and that the content of the resources hasn't
440      * changed by calling <code>validateEdit</code> for a given file on
441      * <tt>IWorkspace</tt>.
442      *
443      * @param resources the resources to be checked
444      * @param shell the Shell passed to <code>validateEdit</code> as a context
445      * @return returns <code>true</code> if all resources are committable, <code>false</code> otherwise
446      *
447      * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object)
448      */

449     public static boolean validateResources(List JavaDoc resources, Shell shell, String JavaDoc title) {
450         IResource r[]= (IResource[]) resources.toArray(new IResource[resources.size()]);
451         return validateResources(r, shell, title);
452     }
453     
454     /*
455      * Makes the given resources committable. Committable means that all
456      * resources are writeable and that the content of the resources hasn't
457      * changed by calling <code>validateEdit</code> for a given file on
458      * <tt>IWorkspace</tt>.
459      *
460      * @param resources the resources to be checked
461      * @param shell the Shell passed to <code>validateEdit</code> as a context
462      * @return returns <code>true</code> if all resources are committable, <code>false</code> otherwise
463      *
464      * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object)
465      */

466     public static boolean validateResources(IResource[] resources, Shell shell, String JavaDoc title) {
467         
468         // get all readonly files
469
List JavaDoc readOnlyFiles= getReadonlyFiles(resources);
470         if (readOnlyFiles.size() == 0)
471             return true;
472         
473         // get timestamps of readonly files before validateEdit
474
Map oldTimeStamps= createModificationStampMap(readOnlyFiles);
475         
476         IFile[] files= (IFile[]) readOnlyFiles.toArray(new IFile[readOnlyFiles.size()]);
477         IStatus status= ResourcesPlugin.getWorkspace().validateEdit(files, shell);
478         if (! status.isOK()) {
479             String JavaDoc message= getString("ValidateEdit.error.unable_to_perform"); //$NON-NLS-1$
480
displayError(shell, title, status, message);
481             return false;
482         }
483             
484         IStatus modified= null;
485         Map newTimeStamps= createModificationStampMap(readOnlyFiles);
486         for (Iterator iter= oldTimeStamps.keySet().iterator(); iter.hasNext();) {
487             IFile file= (IFile) iter.next();
488             if (file.isReadOnly()) {
489                 IStatus entry= new Status(IStatus.ERROR,
490                                 CompareUIPlugin.getPluginId(),
491                                 VALIDATE_EDIT_PROBLEM,
492                                 getFormattedString("ValidateEdit.error.stillReadonly", file.getFullPath().toString()), //$NON-NLS-1$
493
null);
494                 modified= addStatus(modified, entry);
495             } else if (! oldTimeStamps.get(file).equals(newTimeStamps.get(file))) {
496                 IStatus entry= new Status(IStatus.ERROR,
497                                 CompareUIPlugin.getPluginId(),
498                                 VALIDATE_EDIT_PROBLEM,
499                                 getFormattedString("ValidateEdit.error.fileModified", file.getFullPath().toString()), //$NON-NLS-1$
500
null);
501                 modified= addStatus(modified, entry);
502             }
503         }
504         if (modified != null) {
505             String JavaDoc message= getString("ValidateEdit.error.unable_to_perform"); //$NON-NLS-1$
506
displayError(shell, title, modified, message);
507             return false;
508         }
509         return true;
510     }
511
512     private static void displayError(final Shell shell, final String JavaDoc title, final IStatus status, final String JavaDoc message) {
513         if (Display.getCurrent() != null)
514             ErrorDialog.openError(shell, title, message, status);
515         else {
516             Display.getDefault().syncExec(new Runnable JavaDoc() {
517                 public void run() {
518                     ErrorDialog.openError(shell, title, message, status);
519                 }
520             });
521         }
522     }
523     
524     private static List JavaDoc getReadonlyFiles(IResource[] resources) {
525         List JavaDoc readOnlyFiles= new ArrayList();
526         for (int i= 0; i < resources.length; i++) {
527             IResource resource= resources[i];
528             ResourceAttributes resourceAttributes= resource.getResourceAttributes();
529             if (resource.getType() == IResource.FILE && resourceAttributes != null && resourceAttributes.isReadOnly())
530                 readOnlyFiles.add(resource);
531         }
532         return readOnlyFiles;
533     }
534
535     private static Map createModificationStampMap(List JavaDoc files) {
536         Map map= new HashMap();
537         for (Iterator iter= files.iterator(); iter.hasNext(); ) {
538             IFile file= (IFile)iter.next();
539             map.put(file, new Long JavaDoc(file.getModificationStamp()));
540         }
541         return map;
542     }
543     
544     private static IStatus addStatus(IStatus status, IStatus entry) {
545         
546         if (status == null)
547             return entry;
548             
549         if (status.isMultiStatus()) {
550             ((MultiStatus)status).add(entry);
551             return status;
552         }
553
554         MultiStatus result= new MultiStatus(CompareUIPlugin.getPluginId(),
555             VALIDATE_EDIT_PROBLEM,
556             getString("ValidateEdit.error.unable_to_perform"), null); //$NON-NLS-1$
557
result.add(status);
558         result.add(entry);
559         return result;
560     }
561     
562     // encoding
563

564     public static String JavaDoc readString(IStreamContentAccessor sca, String JavaDoc encoding) throws CoreException {
565         String JavaDoc s = null;
566         try {
567             try {
568                 s= Utilities.readString(sca.getContents(), encoding);
569             } catch (UnsupportedEncodingException e) {
570                 if (!encoding.equals(ResourcesPlugin.getEncoding())) {
571                     s = Utilities.readString(sca.getContents(), ResourcesPlugin.getEncoding());
572                 }
573             }
574         } catch (IOException e) {
575             throw new CoreException(new Status(IStatus.ERROR, CompareUIPlugin.PLUGIN_ID, 0, e.getMessage(), e));
576         }
577         return s;
578     }
579     
580     /*
581      * Returns null if an error occurred.
582      */

583     public static String JavaDoc readString(InputStream is, String JavaDoc encoding) throws IOException {
584         if (is == null)
585             return null;
586         BufferedReader reader= null;
587         try {
588             StringBuffer JavaDoc buffer= new StringBuffer JavaDoc();
589             char[] part= new char[2048];
590             int read= 0;
591             reader= new BufferedReader(new InputStreamReader(is, encoding));
592             while ((read= reader.read(part)) != -1)
593                 buffer.append(part, 0, read);
594             
595             return buffer.toString();
596         } finally {
597             if (reader != null) {
598                 try {
599                     reader.close();
600                 } catch (IOException ex) {
601                     // silently ignored
602
}
603             }
604         }
605     }
606     
607     public static String JavaDoc getCharset(Object JavaDoc resource) {
608         if (resource instanceof IEncodedStorage) {
609             try {
610                 return ((IEncodedStorage)resource).getCharset();
611             } catch (CoreException ex) {
612                 CompareUIPlugin.log(ex);
613             }
614         }
615         return ResourcesPlugin.getEncoding();
616     }
617     
618     public static byte[] getBytes(String JavaDoc s, String JavaDoc encoding) {
619         byte[] bytes= null;
620         if (s != null) {
621             try {
622                 bytes= s.getBytes(encoding);
623             } catch (UnsupportedEncodingException e) {
624                 bytes= s.getBytes();
625             }
626         }
627         return bytes;
628     }
629
630     public static String JavaDoc readString(IStreamContentAccessor sa) throws CoreException {
631         String JavaDoc encoding= null;
632         if (sa instanceof IEncodedStreamContentAccessor)
633             encoding= ((IEncodedStreamContentAccessor)sa).getCharset();
634         if (encoding == null)
635             encoding= ResourcesPlugin.getEncoding();
636         return Utilities.readString(sa, encoding);
637     }
638
639     public static void close(InputStream is) {
640         if (is != null) {
641             try {
642                 is.close();
643             } catch (IOException ex) {
644                 // silently ignored
645
}
646         }
647     }
648
649     public static IResource getFirstResource(ISelection selection) {
650         IResource[] resources = getResources(selection);
651         if (resources.length > 0)
652             return resources[0];
653         return null;
654     }
655     
656     public static Object JavaDoc getAdapter(Object JavaDoc element, Class JavaDoc adapterType, boolean load) {
657         if (adapterType.isInstance(element))
658             return element;
659         if (element instanceof IAdaptable) {
660             Object JavaDoc adapted = ((IAdaptable) element).getAdapter(adapterType);
661             if (adapterType.isInstance(adapted))
662                 return adapted;
663         }
664         if (load) {
665             Object JavaDoc adapted = Platform.getAdapterManager().loadAdapter(element, adapterType.getName());
666             if (adapterType.isInstance(adapted))
667                 return adapted;
668         } else {
669             Object JavaDoc adapted = Platform.getAdapterManager().getAdapter(element, adapterType);
670             if (adapterType.isInstance(adapted))
671                 return adapted;
672         }
673         return null;
674     }
675     
676     public static Object JavaDoc getAdapter(Object JavaDoc element, Class JavaDoc adapterType) {
677         return getAdapter(element, adapterType, false);
678     }
679     
680     public static ITypedElement getLeg(char type, Object JavaDoc input) {
681         if (input instanceof ICompareInput) {
682             switch (type) {
683             case MergeViewerContentProvider.ANCESTOR_CONTRIBUTOR:
684                 return ((ICompareInput)input).getAncestor();
685             case MergeViewerContentProvider.LEFT_CONTRIBUTOR:
686                 return ((ICompareInput)input).getLeft();
687             case MergeViewerContentProvider.RIGHT_CONTRIBUTOR:
688                 return ((ICompareInput)input).getRight();
689             }
690         }
691         return null;
692     }
693     
694     public static IDocument getDocument(char type, Object JavaDoc element, boolean isUsingDefaultContentProvider, boolean canHaveSharedDocument) {
695         ITypedElement te= getLeg(type, element);
696         if (te == null)
697             return null;
698         if (te instanceof IDocument)
699             return (IDocument) te;
700         if (te instanceof IDocumentRange)
701             return ((IDocumentRange) te).getDocument();
702         if (te instanceof IStreamContentAccessor)
703             return DocumentManager.get(te);
704         if (isUsingDefaultContentProvider && canHaveSharedDocument) {
705             ISharedDocumentAdapter sda = (ISharedDocumentAdapter)Utilities.getAdapter(te, ISharedDocumentAdapter.class, true);
706             if (sda != null) {
707                 IEditorInput input = sda.getDocumentKey(element);
708                 if (input != null) {
709                     IDocumentProvider provider = SharedDocumentAdapter.getDocumentProvider(input);
710                     if (provider != null)
711                         return provider.getDocument(input);
712                 }
713             }
714         }
715         return null;
716     }
717     
718     /**
719      * Return whether either the left or right sides of the given input
720      * represents a hunk. A hunk is a portion of a file.
721      * @param input the compare input
722      * @return whether the left or right side of the input represents a hunk
723      */

724     public static boolean isHunk(Object JavaDoc input) {
725         if (input != null && input instanceof DiffNode){
726             ITypedElement right = ((DiffNode) input).getRight();
727             if (right != null) {
728                 Object JavaDoc element = Utilities.getAdapter(right, IHunk.class);
729                 if (element instanceof IHunk)
730                     return true;
731             }
732             ITypedElement left = ((DiffNode) input).getLeft();
733             if (left != null) {
734                 Object JavaDoc element = Utilities.getAdapter(left, IHunk.class);
735                 if (element instanceof IHunk)
736                     return true;
737             }
738         }
739         return false;
740     }
741     
742     public static void schedule(Job job, IWorkbenchSite site) {
743         if (site != null) {
744             IWorkbenchSiteProgressService siteProgress = (IWorkbenchSiteProgressService) site.getAdapter(IWorkbenchSiteProgressService.class);
745             if (siteProgress != null) {
746                 siteProgress.schedule(job, 0, true /* use half-busy cursor */);
747                 return;
748             }
749         }
750         job.schedule();
751     }
752
753     public static void runInUIThread(final Runnable JavaDoc runnable) {
754         if (Display.getCurrent() != null) {
755             BusyIndicator.showWhile(Display.getCurrent(), runnable);
756         } else {
757             Display.getDefault().syncExec(new Runnable JavaDoc() {
758                 public void run() {
759                     BusyIndicator.showWhile(Display.getCurrent(), runnable);
760                 }
761             });
762         }
763     }
764 }
765
Popular Tags