1 11 package org.eclipse.compare.internal; 12 13 import java.io.*; 14 import java.util.*; 15 import java.util.List ; 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 45 public class Utilities { 46 47 private static final IPath ICONS_PATH= new Path("$nl$/icons/full/"); 49 public static IWorkbenchPartSite findSite(Control c) { 50 while (c != null && !c.isDisposed()) { 51 Object 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 data= c.getData(); 62 if (data instanceof CompareEditor) 63 return ((CompareEditor)data).getActionBars(); 64 65 if (data instanceof IViewPart) 67 return ((IViewPart)data).getViewSite().getActionBars(); 68 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 key, boolean dflt) { 82 if (cc != null) { 83 Object value= cc.getProperty(key); 84 if (value instanceof Boolean ) 85 return ((Boolean ) value).booleanValue(); 86 } 87 return dflt; 88 } 89 90 public static void firePropertyChange(ListenerList listenerList, Object source, String property, Object old, Object 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 Runnable runnable = new Runnable () { 100 public void run() { 101 if (listenerList != null) { 102 Object [] 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 { 107 listener.propertyChange(event); 108 } 109 public void handleException(Throwable exception) { 110 } 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 type) { 129 ArrayList tmp= new ArrayList(); 130 if (selection instanceof IStructuredSelection) { 131 Object [] s= ((IStructuredSelection)selection).toArray(); 132 133 for (int i= 0; i < s.length; i++) { 134 IResource resource= null; 135 Object 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 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 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 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 } 207 } 208 209 return bos.toByteArray(); 210 } 211 212 public static IPath getIconPath(Display display) { 213 return ICONS_PATH; 214 } 215 216 219 public static void initAction(IAction a, ResourceBundle bundle, String prefix) { 220 221 String labelKey= "label"; String tooltipKey= "tooltip"; String imageKey= "image"; String descriptionKey= "description"; 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 relPath= getString(bundle, imageKey, null); 238 if (relPath != null && relPath.trim().length() > 0) { 239 240 String dPath; 241 String ePath; 242 243 if (relPath.indexOf("/") >= 0) { String path= relPath.substring(1); 245 dPath= 'd' + path; 246 ePath= 'e' + path; 247 } else { 248 dPath= "dlcl16/" + relPath; ePath= "elcl16/" + relPath; } 251 252 ImageDescriptor id= CompareUIPlugin.getImageDescriptor(dPath); 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 prefix, boolean checked) { 264 265 String tooltip= null; 266 if (checked) 267 tooltip= getString(bundle, prefix + "tooltip.checked", null); else 269 tooltip= getString(bundle, prefix + "tooltip.unchecked", null); if (tooltip == null) 271 tooltip= getString(bundle, prefix + "tooltip", null); 273 if (tooltip != null) 274 a.setToolTipText(tooltip); 275 276 String description= null; 277 if (checked) 278 description= getString(bundle, prefix + "description.checked", null); else 280 description= getString(bundle, prefix + "description.unchecked", null); if (description == null) 282 description= getString(bundle, prefix + "description", null); 284 if (description != null) 285 a.setDescription(description); 286 287 } 288 289 public static String getString(ResourceBundle bundle, String key, String dfltValue) { 290 291 if (bundle != null) { 292 try { 293 return bundle.getString(key); 294 } catch (MissingResourceException x) { 295 } 297 } 298 return dfltValue; 299 } 300 301 public static String getFormattedString(ResourceBundle bundle, String key, String arg) { 302 303 if (bundle != null) { 304 try { 305 return MessageFormat.format(bundle.getString(key), new String [] { arg }); 306 } catch (MissingResourceException x) { 307 CompareUIPlugin.log(x); 308 } 309 } 310 return "!" + key + "!"; } 312 313 public static String getString(String key) { 314 try { 315 return CompareUI.getResourceBundle().getString(key); 316 } catch (MissingResourceException e) { 317 return "!" + key + "!"; } 319 } 320 321 public static String getFormattedString(String key, String arg) { 322 try { 323 return MessageFormat.format(CompareUI.getResourceBundle().getString(key), new String [] { arg }); 324 } catch (MissingResourceException e) { 325 return "!" + key + "!"; } 327 } 328 329 public static String getFormattedString(String key, String arg0, String arg1) { 330 try { 331 return MessageFormat.format(CompareUI.getResourceBundle().getString(key), new String [] { arg0, arg1 }); 332 } catch (MissingResourceException e) { 333 return "!" + key + "!"; } 335 } 336 337 public static String getString(ResourceBundle bundle, String key) { 338 return getString(bundle, key, key); 339 } 340 341 public static int getInteger(ResourceBundle bundle, String key, int dfltValue) { 342 343 if (bundle != null) { 344 try { 345 String s= bundle.getString(key); 346 if (s != null) 347 return Integer.parseInt(s); 348 } catch (NumberFormatException x) { 349 CompareUIPlugin.log(x); 350 } catch (MissingResourceException x) { 351 } 353 } 354 return dfltValue; 355 } 356 357 361 401 402 403 404 408 private static final int VALIDATE_EDIT_PROBLEM= 10004; 409 410 413 public static boolean RUNNING_TESTS = false; 414 415 419 public static boolean TESTING_FLUSH_ON_COMPARE_INPUT_CHANGE = false; 420 421 433 public static boolean validateResource(IResource resource, Shell shell, String title) { 434 return validateResources(new IResource[] { resource }, shell, title); 435 } 436 437 449 public static boolean validateResources(List resources, Shell shell, String title) { 450 IResource r[]= (IResource[]) resources.toArray(new IResource[resources.size()]); 451 return validateResources(r, shell, title); 452 } 453 454 466 public static boolean validateResources(IResource[] resources, Shell shell, String title) { 467 468 List readOnlyFiles= getReadonlyFiles(resources); 470 if (readOnlyFiles.size() == 0) 471 return true; 472 473 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 message= getString("ValidateEdit.error.unable_to_perform"); 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()), 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()), null); 501 modified= addStatus(modified, entry); 502 } 503 } 504 if (modified != null) { 505 String message= getString("ValidateEdit.error.unable_to_perform"); displayError(shell, title, modified, message); 507 return false; 508 } 509 return true; 510 } 511 512 private static void displayError(final Shell shell, final String title, final IStatus status, final String message) { 513 if (Display.getCurrent() != null) 514 ErrorDialog.openError(shell, title, message, status); 515 else { 516 Display.getDefault().syncExec(new Runnable () { 517 public void run() { 518 ErrorDialog.openError(shell, title, message, status); 519 } 520 }); 521 } 522 } 523 524 private static List getReadonlyFiles(IResource[] resources) { 525 List 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 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 (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); result.add(status); 558 result.add(entry); 559 return result; 560 } 561 562 564 public static String readString(IStreamContentAccessor sca, String encoding) throws CoreException { 565 String 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 583 public static String readString(InputStream is, String encoding) throws IOException { 584 if (is == null) 585 return null; 586 BufferedReader reader= null; 587 try { 588 StringBuffer buffer= new StringBuffer (); 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 } 603 } 604 } 605 } 606 607 public static String getCharset(Object 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 s, String 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 readString(IStreamContentAccessor sa) throws CoreException { 631 String 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 } 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 getAdapter(Object element, Class adapterType, boolean load) { 657 if (adapterType.isInstance(element)) 658 return element; 659 if (element instanceof IAdaptable) { 660 Object adapted = ((IAdaptable) element).getAdapter(adapterType); 661 if (adapterType.isInstance(adapted)) 662 return adapted; 663 } 664 if (load) { 665 Object adapted = Platform.getAdapterManager().loadAdapter(element, adapterType.getName()); 666 if (adapterType.isInstance(adapted)) 667 return adapted; 668 } else { 669 Object adapted = Platform.getAdapterManager().getAdapter(element, adapterType); 670 if (adapterType.isInstance(adapted)) 671 return adapted; 672 } 673 return null; 674 } 675 676 public static Object getAdapter(Object element, Class adapterType) { 677 return getAdapter(element, adapterType, false); 678 } 679 680 public static ITypedElement getLeg(char type, Object 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 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 724 public static boolean isHunk(Object input) { 725 if (input != null && input instanceof DiffNode){ 726 ITypedElement right = ((DiffNode) input).getRight(); 727 if (right != null) { 728 Object 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 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 ); 747 return; 748 } 749 } 750 job.schedule(); 751 } 752 753 public static void runInUIThread(final Runnable runnable) { 754 if (Display.getCurrent() != null) { 755 BusyIndicator.showWhile(Display.getCurrent(), runnable); 756 } else { 757 Display.getDefault().syncExec(new Runnable () { 758 public void run() { 759 BusyIndicator.showWhile(Display.getCurrent(), runnable); 760 } 761 }); 762 } 763 } 764 } 765 | Popular Tags |