1 19 20 package org.openide.util; 21 22 import java.awt.BorderLayout ; 23 import java.awt.Component ; 24 import java.awt.Container ; 25 import java.awt.Cursor ; 26 import java.awt.Dialog ; 27 import java.awt.Dimension ; 28 import java.awt.Frame ; 29 import java.awt.Graphics ; 30 import java.awt.GraphicsConfiguration ; 31 import java.awt.GraphicsEnvironment ; 32 import java.awt.Image ; 33 import java.awt.Insets ; 34 import java.awt.KeyboardFocusManager ; 35 import java.awt.Point ; 36 import java.awt.Rectangle ; 37 import java.awt.Toolkit ; 38 import java.awt.Window ; 39 import java.awt.event.ActionEvent ; 40 import java.awt.event.ActionListener ; 41 import java.awt.event.KeyEvent ; 42 import java.awt.image.BufferedImage ; 43 import java.io.BufferedReader ; 44 import java.io.File ; 45 import java.io.IOException ; 46 import java.io.InputStreamReader ; 47 import java.lang.ref.Reference ; 48 import java.lang.ref.ReferenceQueue ; 49 import java.lang.ref.SoftReference ; 50 import java.lang.reflect.Field ; 51 import java.lang.reflect.Method ; 52 import java.lang.reflect.Modifier ; 53 import java.net.MalformedURLException ; 54 import java.net.URI ; 55 import java.net.URISyntaxException ; 56 import java.net.URL ; 57 import java.text.BreakIterator ; 58 import java.util.ArrayList ; 59 import java.util.Arrays ; 60 import java.util.Collection ; 61 import java.util.Collections ; 62 import java.util.Comparator ; 63 import java.util.Enumeration ; 64 import java.util.HashMap ; 65 import java.util.HashSet ; 66 import java.util.Iterator ; 67 import java.util.LinkedList ; 68 import java.util.List ; 69 import java.util.Locale ; 70 import java.util.Map ; 71 import java.util.NoSuchElementException ; 72 import java.util.Set ; 73 import java.util.StringTokenizer ; 74 import java.util.TreeSet ; 75 import java.util.Vector ; 76 import java.util.logging.Level ; 77 import java.util.logging.Logger ; 78 import javax.swing.Action ; 79 import javax.swing.Icon ; 80 import javax.swing.ImageIcon ; 81 import javax.swing.JLabel ; 82 import javax.swing.JMenuItem ; 83 import javax.swing.JPopupMenu ; 84 import javax.swing.JSeparator ; 85 import javax.swing.KeyStroke ; 86 import javax.swing.SwingUtilities ; 87 import javax.swing.Timer ; 88 import org.netbeans.modules.openide.util.AWTBridge; 89 import org.openide.util.actions.Presenter; 90 91 95 public final class Utilities { 96 97 public static final int OS_WINNT = 1 << 0; 98 99 100 public static final int OS_WIN95 = OS_WINNT << 1; 101 102 103 public static final int OS_WIN98 = OS_WIN95 << 1; 104 105 106 public static final int OS_SOLARIS = OS_WIN98 << 1; 107 108 109 public static final int OS_LINUX = OS_SOLARIS << 1; 110 111 112 public static final int OS_HP = OS_LINUX << 1; 113 114 115 public static final int OS_AIX = OS_HP << 1; 116 117 118 public static final int OS_IRIX = OS_AIX << 1; 119 120 121 public static final int OS_SUNOS = OS_IRIX << 1; 122 123 124 public static final int OS_TRU64 = OS_SUNOS << 1; 125 126 127 @Deprecated 128 public static final int OS_DEC = OS_TRU64 << 1; 129 130 131 public static final int OS_OS2 = OS_DEC << 1; 132 133 134 public static final int OS_MAC = OS_OS2 << 1; 135 136 137 public static final int OS_WIN2000 = OS_MAC << 1; 138 139 140 public static final int OS_VMS = OS_WIN2000 << 1; 141 142 146 public static final int OS_WIN_OTHER = OS_VMS << 1; 147 148 149 public static final int OS_OTHER = OS_WIN_OTHER << 1; 150 151 154 public static final int OS_FREEBSD = OS_OTHER << 1; 155 156 157 public static final int OS_WINDOWS_MASK = OS_WINNT | OS_WIN95 | OS_WIN98 | OS_WIN2000 | OS_WIN_OTHER; 158 159 160 public static final int OS_UNIX_MASK = OS_SOLARIS | OS_LINUX | OS_HP | OS_AIX | OS_IRIX | OS_SUNOS | OS_TRU64 | 161 OS_MAC | OS_FREEBSD; 162 163 164 public static final int TYPICAL_WINDOWS_TASKBAR_HEIGHT = 27; 165 166 167 private static final int TYPICAL_MACOSX_MENU_HEIGHT = 24; 168 169 private static ActiveQueue activeReferenceQueue; 170 171 173 private static Reference <Object > namesAndValues; 174 175 176 private static int operatingSystem = -1; 177 private static final String [] keywords = new String [] { 178 179 "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" }; 191 private static Timer clearIntrospector; 192 private static ActionListener doClear; 193 private static final int CTRL_WILDCARD_MASK = 32768; 194 private static final int ALT_WILDCARD_MASK = CTRL_WILDCARD_MASK * 2; 195 196 private static final String TRANS_LOCK = "TRANS_LOCK"; 198 199 200 private static Object transLoader; 201 202 203 private static RE transExp; 204 205 209 210 private static Object actionClassForPopupMenu; 211 212 213 private static Lookup global; 214 215 private Utilities() { 216 } 217 218 258 public static synchronized ReferenceQueue <Object > activeReferenceQueue() { 259 if (activeReferenceQueue == null) { 260 activeReferenceQueue = new ActiveQueue(false); 261 } 262 263 activeReferenceQueue.ping(); 264 265 return activeReferenceQueue; 266 } 267 268 271 public static final int getOperatingSystem() { 272 if (operatingSystem == -1) { 273 String osName = System.getProperty("os.name"); 274 275 if ("Windows NT".equals(osName)) { operatingSystem = OS_WINNT; 277 } else if ("Windows 95".equals(osName)) { operatingSystem = OS_WIN95; 279 } else if ("Windows 98".equals(osName)) { operatingSystem = OS_WIN98; 281 } else if ("Windows 2000".equals(osName)) { operatingSystem = OS_WIN2000; 283 } else if (osName.startsWith("Windows ")) { operatingSystem = OS_WIN_OTHER; 285 } else if ("Solaris".equals(osName)) { operatingSystem = OS_SOLARIS; 287 } else if (osName.startsWith("SunOS")) { operatingSystem = OS_SOLARIS; 289 } 290 else if (osName.endsWith("Linux")) { operatingSystem = OS_LINUX; 293 } else if ("HP-UX".equals(osName)) { operatingSystem = OS_HP; 295 } else if ("AIX".equals(osName)) { operatingSystem = OS_AIX; 297 } else if ("Irix".equals(osName)) { operatingSystem = OS_IRIX; 299 } else if ("SunOS".equals(osName)) { operatingSystem = OS_SUNOS; 301 } else if ("Digital UNIX".equals(osName)) { operatingSystem = OS_TRU64; 303 } else if ("OS/2".equals(osName)) { operatingSystem = OS_OS2; 305 } else if ("OpenVMS".equals(osName)) { operatingSystem = OS_VMS; 307 } else if (osName.equals("Mac OS X")) { operatingSystem = OS_MAC; 309 } else if (osName.startsWith("Darwin")) { operatingSystem = OS_MAC; 311 } else if (osName.toLowerCase(Locale.US).startsWith("freebsd")) { operatingSystem = OS_FREEBSD; 313 } else { 314 operatingSystem = OS_OTHER; 315 } 316 } 317 318 return operatingSystem; 319 } 320 321 324 public static final boolean isWindows() { 325 return (getOperatingSystem() & OS_WINDOWS_MASK) != 0; 326 } 327 328 332 public static final boolean isMac() { 333 return (getOperatingSystem() & OS_MAC) != 0; 334 } 335 336 340 public static final boolean isUnix() { 341 return (getOperatingSystem() & OS_UNIX_MASK) != 0; 342 } 343 344 final static void resetOperatingSystem() { 346 operatingSystem = -1; 347 } 348 349 353 public static final boolean isJavaIdentifier(String id) { 354 if (id == null) { 355 return false; 356 } 357 358 if (id.equals("")) { 359 return false; 360 } 361 362 if (!(java.lang.Character.isJavaIdentifierStart(id.charAt(0)))) { 363 return false; 364 } 365 366 for (int i = 1; i < id.length(); i++) { 367 if (!(java.lang.Character.isJavaIdentifierPart(id.charAt(i)))) { 368 return false; 369 } 370 } 371 372 return Arrays.binarySearch(keywords, id) < 0; 373 } 374 375 381 public static java.beans.BeanInfo getBeanInfo(Class clazz) 382 throws java.beans.IntrospectionException { 383 java.beans.BeanInfo bi; 384 385 try { 386 bi = java.beans.Introspector.getBeanInfo(clazz); 387 } catch (java.beans.IntrospectionException ie) { 388 Exceptions.attachMessage(ie, 389 "Encountered while introspecting " + 390 clazz.getName()); throw ie; 392 } catch (Error e) { 393 Exceptions.attachMessage(e, 395 "Encountered while introspecting " + 396 clazz.getName()); throw e; 398 } 399 400 if (java.awt.Component .class.isAssignableFrom(clazz)) { 401 java.beans.PropertyDescriptor [] pds = bi.getPropertyDescriptors(); 402 403 for (int i = 0; i < pds.length; i++) { 404 if (pds[i].getName().equals("cursor")) { 406 try { 407 Method getter = Component .class.getDeclaredMethod("getCursor", new Class [0]); Method setter = Component .class.getDeclaredMethod("setCursor", new Class [] { Cursor .class }); pds[i] = new java.beans.PropertyDescriptor ("cursor", getter, setter); } catch (NoSuchMethodException e) { 411 e.printStackTrace(); 412 } 413 414 break; 415 } 416 } 417 } 418 419 if (bi != null) { 421 if (clearIntrospector == null) { 422 doClear = new ActionListener () { 423 public void actionPerformed(ActionEvent ev) { 424 java.beans.Introspector.flushCaches(); 425 } 426 }; 427 clearIntrospector = new Timer (15000, doClear); 428 clearIntrospector.setRepeats(false); 429 } 430 431 clearIntrospector.restart(); 432 } 433 434 return bi; 435 } 436 437 444 public static java.beans.BeanInfo getBeanInfo(Class clazz, Class stopClass) 445 throws java.beans.IntrospectionException { 446 return java.beans.Introspector.getBeanInfo(clazz, stopClass); 447 } 448 449 458 @Deprecated 459 public static String [] wrapStringToArray(String original, int width, boolean wrapWords, boolean removeNewLines) { 460 BreakIterator bi = (wrapWords ? BreakIterator.getWordInstance() : BreakIterator.getCharacterInstance()); 461 462 return wrapStringToArray(original, width, bi, removeNewLines); 463 } 464 465 472 public static String [] wrapStringToArray( 473 String original, int width, BreakIterator breakIterator, boolean removeNewLines 474 ) { 475 if (original.length() == 0) { 476 return new String [] { original }; 477 } 478 479 String [] workingSet; 480 481 if (removeNewLines) { 484 original = trimString(original); 485 original = original.replace('\n', ' '); 486 workingSet = new String [] { original }; 487 } else { 488 StringTokenizer tokens = new StringTokenizer (original, "\n"); int len = tokens.countTokens(); 490 workingSet = new String [len]; 491 492 for (int i = 0; i < len; i++) { 493 workingSet[i] = tokens.nextToken(); 494 } 495 } 496 497 if (width < 1) { 498 width = 1; 499 } 500 501 if (original.length() <= width) { 502 return workingSet; 503 } 504 505 widthcheck: { 506 boolean ok = true; 507 508 for (int i = 0; i < workingSet.length; i++) { 509 ok = ok && (workingSet[i].length() < width); 510 511 if (!ok) { 512 break widthcheck; 513 } 514 } 515 516 return workingSet; 517 } 518 519 java.util.ArrayList <String > lines = new java.util.ArrayList <String >(); 520 521 int lineStart = 0; 523 for (int i = 0; i < workingSet.length; i++) { 524 if (workingSet[i].length() < width) { 525 lines.add(workingSet[i]); 526 } else { 527 breakIterator.setText(workingSet[i]); 528 529 int nextStart = breakIterator.next(); 530 int prevStart = 0; 531 532 do { 533 while (((nextStart - lineStart) < width) && (nextStart != BreakIterator.DONE)) { 534 prevStart = nextStart; 535 nextStart = breakIterator.next(); 536 } 537 538 if (nextStart == BreakIterator.DONE) { 539 nextStart = prevStart = workingSet[i].length(); 540 } 541 542 if (prevStart == 0) { 543 prevStart = nextStart; 544 } 545 546 lines.add(workingSet[i].substring(lineStart, prevStart)); 547 548 lineStart = prevStart; 549 prevStart = 0; 550 } while (lineStart < workingSet[i].length()); 551 552 lineStart = 0; 553 } 554 } 555 556 String [] s = new String [lines.size()]; 557 558 return lines.toArray(s); 559 } 560 561 565 private static String trimString(String s) { 566 int idx = 0; 567 char c; 568 final int slen = s.length(); 569 570 if (slen == 0) { 571 return s; 572 } 573 574 do { 575 c = s.charAt(idx++); 576 } while (((c == '\n') || (c == '\r')) && (idx < slen)); 577 578 s = s.substring(--idx); 579 idx = s.length() - 1; 580 581 if (idx < 0) { 582 return s; 583 } 584 585 do { 586 c = s.charAt(idx--); 587 } while (((c == '\n') || (c == '\r')) && (idx >= 0)); 588 589 return s.substring(0, idx + 2); 590 } 591 592 599 public static String wrapString(String original, int width, BreakIterator breakIterator, boolean removeNewLines) { 600 String [] sarray = wrapStringToArray(original, width, breakIterator, removeNewLines); 601 StringBuffer retBuf = new StringBuffer (); 602 603 for (int i = 0; i < sarray.length; i++) { 604 retBuf.append(sarray[i]); 605 retBuf.append('\n'); 606 } 607 608 return retBuf.toString(); 609 } 610 611 620 @Deprecated 621 public static String wrapString(String original, int width, boolean wrapWords, boolean removeNewLines) { 622 if (removeNewLines) { 625 while (original.startsWith("\n")) 627 original = original.substring(1); 628 629 while (original.endsWith("\n")) 631 original = original.substring(0, original.length() - 1); 632 633 original = original.replace('\n', ' '); 634 } 635 636 if (width < 1) { 637 width = 1; 638 } 639 640 if (original.length() <= width) { 641 return original; 642 } 643 644 java.util.Vector <String > lines = new java.util.Vector <String >(); 645 int lineStart = 0; int lastSpacePos = -1; 647 648 for (int i = 0; i < original.length(); i++) { 649 if (lineStart >= (original.length() - 1)) { 650 break; 651 } 652 653 if (original.charAt(i) == '\n') { 655 lines.addElement(original.substring(lineStart, i)); 656 lineStart = i + 1; 657 lastSpacePos = -1; 658 659 continue; 660 } 661 662 if (Character.isSpaceChar(original.charAt(i))) { 664 lastSpacePos = i; 665 } 666 667 if (i == (original.length() - 1)) { 669 lines.addElement(original.substring(lineStart)); 670 671 break; 672 } 673 674 if ((i - lineStart) == width) { 676 if (wrapWords && (lastSpacePos != -1)) { 677 lines.addElement(original.substring(lineStart, lastSpacePos)); 678 lineStart = lastSpacePos + 1; lastSpacePos = -1; 680 } else { 681 lines.addElement(original.substring(lineStart, i)); 682 lineStart = i; 683 lastSpacePos = -1; 684 } 685 } 686 } 687 688 StringBuffer retBuf = new StringBuffer (); 689 690 for (java.util.Enumeration e = lines.elements(); e.hasMoreElements();) { 691 retBuf.append((String ) e.nextElement()); 692 retBuf.append('\n'); 693 } 694 695 return retBuf.toString(); 696 } 697 698 704 public static String replaceString(String original, String replaceFrom, String replaceTo) { 705 int index = 0; 706 707 if ("".equals(replaceFrom)) { 708 return original; } 710 711 StringBuffer buf = new StringBuffer (); 712 713 while (true) { 714 int pos = original.indexOf(replaceFrom, index); 715 716 if (pos == -1) { 717 buf.append(original.substring(index)); 718 719 return buf.toString(); 720 } 721 722 buf.append(original.substring(index, pos)); 723 buf.append(replaceTo); 724 index = pos + replaceFrom.length(); 725 726 if (index == original.length()) { 727 return buf.toString(); 728 } 729 } 730 } 731 732 736 public static final String pureClassName(final String fullName) { 737 final int index = fullName.indexOf('$'); 738 739 if ((index >= 0) && (index < fullName.length())) { 740 return fullName.substring(index + 1, fullName.length()); 741 } 742 743 return fullName; 744 } 745 746 750 public static final boolean isLargeFrameIcons() { 751 return (getOperatingSystem() == OS_SOLARIS) || (getOperatingSystem() == OS_HP); 752 } 753 754 761 public static int arrayHashCode(Object [] arr) { 762 int c = 0; 763 int len = arr.length; 764 765 for (int i = 0; i < len; i++) { 766 Object o = arr[i]; 767 int v = (o == null) ? 1 : o.hashCode(); 768 c += (v ^ i); 769 } 770 771 return c; 772 } 773 774 787 public static boolean compareObjects(Object o1, Object o2) { 788 return compareObjectsImpl(o1, o2, 1); 789 } 790 791 798 public static boolean compareObjectsImpl(Object o1, Object o2, int checkArraysDepth) { 799 if (o1 == null) { 801 return (o2 == null); 802 } else if (o2 == null) { 803 return false; 804 } 805 806 if (checkArraysDepth > 0) { 808 if ((o1 instanceof Object []) && (o2 instanceof Object [])) { 809 Object [] o1a = (Object []) o1; 812 Object [] o2a = (Object []) o2; 813 int l1 = o1a.length; 814 int l2 = o2a.length; 815 816 if (l1 != l2) { 817 return false; 818 } 819 820 for (int i = 0; i < l1; i++) { 821 if (!compareObjectsImpl(o1a[i], o2a[i], checkArraysDepth - 1)) { 822 return false; 823 } 824 } 825 826 return true; 827 } else if ((o1 instanceof byte[]) && (o2 instanceof byte[])) { 828 byte[] o1a = (byte[]) o1; 829 byte[] o2a = (byte[]) o2; 830 int l1 = o1a.length; 831 int l2 = o2a.length; 832 833 if (l1 != l2) { 834 return false; 835 } 836 837 for (int i = 0; i < l1; i++) 838 if (o1a[i] != o2a[i]) { 839 return false; 840 } 841 842 return true; 843 } else if ((o1 instanceof short[]) && (o2 instanceof short[])) { 844 short[] o1a = (short[]) o1; 845 short[] o2a = (short[]) o2; 846 int l1 = o1a.length; 847 int l2 = o2a.length; 848 849 if (l1 != l2) { 850 return false; 851 } 852 853 for (int i = 0; i < l1; i++) 854 if (o1a[i] != o2a[i]) { 855 return false; 856 } 857 858 return true; 859 } else if ((o1 instanceof int[]) && (o2 instanceof int[])) { 860 int[] o1a = (int[]) o1; 861 int[] o2a = (int[]) o2; 862 int l1 = o1a.length; 863 int l2 = o2a.length; 864 865 if (l1 != l2) { 866 return false; 867 } 868 869 for (int i = 0; i < l1; i++) 870 if (o1a[i] != o2a[i]) { 871 return false; 872 } 873 874 return true; 875 } else if ((o1 instanceof long[]) && (o2 instanceof long[])) { 876 long[] o1a = (long[]) o1; 877 long[] o2a = (long[]) o2; 878 int l1 = o1a.length; 879 int l2 = o2a.length; 880 881 if (l1 != l2) { 882 return false; 883 } 884 885 for (int i = 0; i < l1; i++) 886 if (o1a[i] != o2a[i]) { 887 return false; 888 } 889 890 return true; 891 } else if ((o1 instanceof float[]) && (o2 instanceof float[])) { 892 float[] o1a = (float[]) o1; 893 float[] o2a = (float[]) o2; 894 int l1 = o1a.length; 895 int l2 = o2a.length; 896 897 if (l1 != l2) { 898 return false; 899 } 900 901 for (int i = 0; i < l1; i++) 902 if (o1a[i] != o2a[i]) { 903 return false; 904 } 905 906 return true; 907 } else if ((o1 instanceof double[]) && (o2 instanceof double[])) { 908 double[] o1a = (double[]) o1; 909 double[] o2a = (double[]) o2; 910 int l1 = o1a.length; 911 int l2 = o2a.length; 912 913 if (l1 != l2) { 914 return false; 915 } 916 917 for (int i = 0; i < l1; i++) 918 if (o1a[i] != o2a[i]) { 919 return false; 920 } 921 922 return true; 923 } else if ((o1 instanceof char[]) && (o2 instanceof char[])) { 924 char[] o1a = (char[]) o1; 925 char[] o2a = (char[]) o2; 926 int l1 = o1a.length; 927 int l2 = o2a.length; 928 929 if (l1 != l2) { 930 return false; 931 } 932 933 for (int i = 0; i < l1; i++) 934 if (o1a[i] != o2a[i]) { 935 return false; 936 } 937 938 return true; 939 } else if ((o1 instanceof boolean[]) && (o2 instanceof boolean[])) { 940 boolean[] o1a = (boolean[]) o1; 941 boolean[] o2a = (boolean[]) o2; 942 int l1 = o1a.length; 943 int l2 = o2a.length; 944 945 if (l1 != l2) { 946 return false; 947 } 948 949 for (int i = 0; i < l1; i++) 950 if (o1a[i] != o2a[i]) { 951 return false; 952 } 953 954 return true; 955 } 956 957 } 959 960 return o1.equals(o2); 962 } 963 964 969 public static String getClassName(Class clazz) { 970 if (clazz.isArray()) { 972 return getClassName(clazz.getComponentType()) + "[]"; } else { 974 return clazz.getName(); 975 } 976 } 977 978 983 public static String getShortClassName(Class clazz) { 984 if (clazz.isArray()) { 986 return getShortClassName(clazz.getComponentType()) + "[]"; } 988 989 String name = clazz.getName().replace('$', '.'); 990 991 return name.substring(name.lastIndexOf(".") + 1, name.length()); } 993 994 1001 public static Object toPrimitiveArray(Object [] array) { 1002 if (array instanceof Integer []) { 1003 int[] r = new int[array.length]; 1004 int i; 1005 int k = array.length; 1006 1007 for (i = 0; i < k; i++) 1008 r[i] = (((Integer ) array[i]) == null) ? 0 : ((Integer ) array[i]).intValue(); 1009 1010 return r; 1011 } 1012 1013 if (array instanceof Boolean []) { 1014 boolean[] r = new boolean[array.length]; 1015 int i; 1016 int k = array.length; 1017 1018 for (i = 0; i < k; i++) 1019 r[i] = (((Boolean ) array[i]) == null) ? false : ((Boolean ) array[i]).booleanValue(); 1020 1021 return r; 1022 } 1023 1024 if (array instanceof Byte []) { 1025 byte[] r = new byte[array.length]; 1026 int i; 1027 int k = array.length; 1028 1029 for (i = 0; i < k; i++) 1030 r[i] = (((Byte ) array[i]) == null) ? 0 : ((Byte ) array[i]).byteValue(); 1031 1032 return r; 1033 } 1034 1035 if (array instanceof Character []) { 1036 char[] r = new char[array.length]; 1037 int i; 1038 int k = array.length; 1039 1040 for (i = 0; i < k; i++) 1041 r[i] = (((Character ) array[i]) == null) ? 0 : ((Character ) array[i]).charValue(); 1042 1043 return r; 1044 } 1045 1046 if (array instanceof Double []) { 1047 double[] r = new double[array.length]; 1048 int i; 1049 int k = array.length; 1050 1051 for (i = 0; i < k; i++) 1052 r[i] = (((Double ) array[i]) == null) ? 0 : ((Double ) array[i]).doubleValue(); 1053 1054 return r; 1055 } 1056 1057 if (array instanceof Float []) { 1058 float[] r = new float[array.length]; 1059 int i; 1060 int k = array.length; 1061 1062 for (i = 0; i < k; i++) 1063 r[i] = (((Float ) array[i]) == null) ? 0 : ((Float ) array[i]).floatValue(); 1064 1065 return r; 1066 } 1067 1068 if (array instanceof Long []) { 1069 long[] r = new long[array.length]; 1070 int i; 1071 int k = array.length; 1072 1073 for (i = 0; i < k; i++) 1074 r[i] = (((Long ) array[i]) == null) ? 0 : ((Long ) array[i]).longValue(); 1075 1076 return r; 1077 } 1078 1079 if (array instanceof Short []) { 1080 short[] r = new short[array.length]; 1081 int i; 1082 int k = array.length; 1083 1084 for (i = 0; i < k; i++) 1085 r[i] = (((Short ) array[i]) == null) ? 0 : ((Short ) array[i]).shortValue(); 1086 1087 return r; 1088 } 1089 1090 throw new IllegalArgumentException (); 1091 } 1092 1093 1100 public static Object [] toObjectArray(Object array) { 1101 if (array instanceof Object []) { 1102 return (Object []) array; 1103 } 1104 1105 if (array instanceof int[]) { 1106 int i; 1107 int k = ((int[]) array).length; 1108 Integer [] r = new Integer [k]; 1109 1110 for (i = 0; i < k; i++) 1111 r[i] = new Integer (((int[]) array)[i]); 1112 1113 return r; 1114 } 1115 1116 if (array instanceof boolean[]) { 1117 int i; 1118 int k = ((boolean[]) array).length; 1119 Boolean [] r = new Boolean [k]; 1120 1121 for (i = 0; i < k; i++) 1122 r[i] = ((boolean[]) array)[i] ? Boolean.TRUE : Boolean.FALSE; 1123 1124 return r; 1125 } 1126 1127 if (array instanceof byte[]) { 1128 int i; 1129 int k = ((byte[]) array).length; 1130 Byte [] r = new Byte [k]; 1131 1132 for (i = 0; i < k; i++) 1133 r[i] = new Byte (((byte[]) array)[i]); 1134 1135 return r; 1136 } 1137 1138 if (array instanceof char[]) { 1139 int i; 1140 int k = ((char[]) array).length; 1141 Character [] r = new Character [k]; 1142 1143 for (i = 0; i < k; i++) 1144 r[i] = new Character (((char[]) array)[i]); 1145 1146 return r; 1147 } 1148 1149 if (array instanceof double[]) { 1150 int i; 1151 int k = ((double[]) array).length; 1152 Double [] r = new Double [k]; 1153 1154 for (i = 0; i < k; i++) 1155 r[i] = new Double (((double[]) array)[i]); 1156 1157 return r; 1158 } 1159 1160 if (array instanceof float[]) { 1161 int i; 1162 int k = ((float[]) array).length; 1163 Float [] r = new Float [k]; 1164 1165 for (i = 0; i < k; i++) 1166 r[i] = new Float (((float[]) array)[i]); 1167 1168 return r; 1169 } 1170 1171 if (array instanceof long[]) { 1172 int i; 1173 int k = ((long[]) array).length; 1174 Long [] r = new Long [k]; 1175 1176 for (i = 0; i < k; i++) 1177 r[i] = new Long (((long[]) array)[i]); 1178 1179 return r; 1180 } 1181 1182 if (array instanceof short[]) { 1183 int i; 1184 int k = ((short[]) array).length; 1185 Short [] r = new Short [k]; 1186 1187 for (i = 0; i < k; i++) 1188 r[i] = new Short (((short[]) array)[i]); 1189 1190 return r; 1191 } 1192 1193 throw new IllegalArgumentException (); 1194 } 1195 1196 1202 public static Class getObjectType(Class c) { 1203 if (!c.isPrimitive()) { 1204 return c; 1205 } 1206 1207 if (c == Integer.TYPE) { 1208 return Integer .class; 1209 } 1210 1211 if (c == Boolean.TYPE) { 1212 return Boolean .class; 1213 } 1214 1215 if (c == Byte.TYPE) { 1216 return Byte .class; 1217 } 1218 1219 if (c == Character.TYPE) { 1220 return Character .class; 1221 } 1222 1223 if (c == Double.TYPE) { 1224 return Double .class; 1225 } 1226 1227 if (c == Float.TYPE) { 1228 return Float .class; 1229 } 1230 1231 if (c == Long.TYPE) { 1232 return Long .class; 1233 } 1234 1235 if (c == Short.TYPE) { 1236 return Short .class; 1237 } 1238 1239 throw new IllegalArgumentException (); 1240 } 1241 1242 1248 public static Class getPrimitiveType(Class c) { 1249 if (!c.isPrimitive()) { 1250 return c; 1251 } 1252 1253 if (c == Integer .class) { 1254 return Integer.TYPE; 1255 } 1256 1257 if (c == Boolean .class) { 1258 return Boolean.TYPE; 1259 } 1260 1261 if (c == Byte .class) { 1262 return Byte.TYPE; 1263 } 1264 1265 if (c == Character .class) { 1266 return Character.TYPE; 1267 } 1268 1269 if (c == Double .class) { 1270 return Double.TYPE; 1271 } 1272 1273 if (c == Float .class) { 1274 return Float.TYPE; 1275 } 1276 1277 if (c == Long .class) { 1278 return Long.TYPE; 1279 } 1280 1281 if (c == Short .class) { 1282 return Short.TYPE; 1283 } 1284 1285 throw new IllegalArgumentException (); 1286 } 1287 1288 1293 public static Component getFocusTraversableComponent(Component c) { 1294 if (c.isFocusable()) { 1295 return c; 1296 } 1297 1298 if (!(c instanceof Container )) { 1299 return null; 1300 } 1301 1302 int i; 1303 int k = ((Container ) c).getComponentCount(); 1304 1305 for (i = 0; i < k; i++) { 1306 Component v = ((Container ) c).getComponent(i); 1307 1308 if (v != null) { 1309 return v; 1310 } 1311 } 1312 1313 return null; 1314 } 1315 1316 1345 public static String [] parseParameters(String s) { 1346 int NULL = 0x0; int INPARAM = 0x1; int INPARAMPENDING = 0x2; int STICK = 0x4; int STICKPENDING = 0x8; Vector <String > params = new Vector <String >(5, 5); 1352 char c; 1353 1354 int state = NULL; 1355 StringBuffer buff = new StringBuffer (20); 1356 int slength = s.length(); 1357 1358 for (int i = 0; i < slength; i++) { 1359 c = s.charAt(i); 1360 1361 if (Character.isWhitespace(c)) { 1362 if (state == NULL) { 1363 if (buff.length() > 0) { 1364 params.addElement(buff.toString()); 1365 buff.setLength(0); 1366 } 1367 } else if (state == STICK) { 1368 params.addElement(buff.toString()); 1369 buff.setLength(0); 1370 state = NULL; 1371 } else if (state == STICKPENDING) { 1372 buff.append('\\'); 1373 params.addElement(buff.toString()); 1374 buff.setLength(0); 1375 state = NULL; 1376 } else if (state == INPARAMPENDING) { 1377 state = INPARAM; 1378 buff.append('\\'); 1379 buff.append(c); 1380 } else { buff.append(c); 1382 } 1383 1384 continue; 1385 } 1386 1387 if (c == '\\') { 1388 if (state == NULL) { 1389 ++i; 1390 1391 if (i < slength) { 1392 char cc = s.charAt(i); 1393 1394 if ((cc == '"') || (cc == '\\')) { 1395 buff.append(cc); 1396 } else if (Character.isWhitespace(cc)) { 1397 buff.append(c); 1398 --i; 1399 } else { 1400 buff.append(c); 1401 buff.append(cc); 1402 } 1403 } else { 1404 buff.append('\\'); 1405 1406 break; 1407 } 1408 1409 continue; 1410 } else if (state == INPARAM) { 1411 state = INPARAMPENDING; 1412 } else if (state == INPARAMPENDING) { 1413 buff.append('\\'); 1414 state = INPARAM; 1415 } else if (state == STICK) { 1416 state = STICKPENDING; 1417 } else if (state == STICKPENDING) { 1418 buff.append('\\'); 1419 state = STICK; 1420 } 1421 1422 continue; 1423 } 1424 1425 if (c == '"') { 1426 if (state == NULL) { 1427 state = INPARAM; 1428 } else if (state == INPARAM) { 1429 state = STICK; 1430 } else if (state == STICK) { 1431 state = INPARAM; 1432 } else if (state == STICKPENDING) { 1433 buff.append('"'); 1434 state = STICK; 1435 } else { buff.append('"'); 1437 state = INPARAM; 1438 } 1439 1440 continue; 1441 } 1442 1443 if (state == INPARAMPENDING) { 1444 buff.append('\\'); 1445 state = INPARAM; 1446 } else if (state == STICKPENDING) { 1447 buff.append('\\'); 1448 state = STICK; 1449 } 1450 1451 buff.append(c); 1452 } 1453 1454 if (state == INPARAM) { 1456 params.addElement(buff.toString()); 1457 } else if ((state & (INPARAMPENDING | STICKPENDING)) != 0) { 1458 buff.append('\\'); 1459 params.addElement(buff.toString()); 1460 } else { 1462 if (buff.length() != 0) { 1463 params.addElement(buff.toString()); 1464 } 1465 } 1466 1467 String [] ret = new String [params.size()]; 1468 params.copyInto(ret); 1469 1470 return ret; 1471 } 1472 1473 1476 public static String escapeParameters(String [] params) { 1477 StringBuffer sb = new StringBuffer (); 1478 1479 for (int i = 0; i < params.length; i++) { 1480 escapeString(params[i], sb); 1481 sb.append(' '); 1482 } 1483 1484 final int len = sb.length(); 1485 1486 if (len > 0) { 1487 sb.setLength(len - 1); 1488 } 1489 1490 return sb.toString().trim(); 1491 } 1492 1493 1496 private static void escapeString(String s, StringBuffer sb) { 1497 if (s.length() == 0) { 1498 sb.append("\"\""); 1499 1500 return; 1501 } 1502 1503 boolean hasSpace = false; 1504 final int sz = sb.length(); 1505 final int slen = s.length(); 1506 char c; 1507 1508 for (int i = 0; i < slen; i++) { 1509 c = s.charAt(i); 1510 1511 if (Character.isWhitespace(c)) { 1512 hasSpace = true; 1513 sb.append(c); 1514 1515 continue; 1516 } 1517 1518 if (c == '\\') { 1519 sb.append('\\').append('\\'); 1520 1521 continue; 1522 } 1523 1524 if (c == '"') { 1525 sb.append('\\').append('"'); 1526 1527 continue; 1528 } 1529 1530 sb.append(c); 1531 } 1532 1533 if (hasSpace) { 1534 sb.insert(sz, '"'); 1535 sb.append('"'); 1536 } 1537 } 1538 1539 1543 1549 private static synchronized HashMap [] initNameAndValues() { 1550 if (namesAndValues != null) { 1551 HashMap [] arr = (HashMap []) namesAndValues.get(); 1552 1553 if (arr != null) { 1554 return arr; 1555 } 1556 } 1557 1558 Field [] fields = KeyEvent .class.getDeclaredFields(); 1559 1560 HashMap <String ,Integer > names = new HashMap <String ,Integer >(((fields.length * 4) / 3) + 5, 0.75f); 1561 HashMap <Integer ,String > values = new HashMap <Integer ,String >(((fields.length * 4) / 3) + 5, 0.75f); 1562 1563 for (int i = 0; i < fields.length; i++) { 1564 if (Modifier.isStatic(fields[i].getModifiers())) { 1565 String name = fields[i].getName(); 1566 1567 if (name.startsWith("VK_")) { 1569 name = name.substring(3); 1571 1572 try { 1573 int numb = fields[i].getInt(null); 1574 Integer value = new Integer (numb); 1575 names.put(name, value); 1576 values.put(value, name); 1577 } catch (IllegalArgumentException ex) { 1578 } catch (IllegalAccessException ex) { 1579 } 1580 } 1581 } 1582 } 1583 1584 if (names.get("CONTEXT_MENU") == null) { 1586 Integer n = new Integer (0x20C); 1587 names.put("CONTEXT_MENU", n); values.put(n, "CONTEXT_MENU"); 1590 n = new Integer (0x20D); 1591 names.put("WINDOWS", n); values.put(n, "WINDOWS"); } 1594 1595 HashMap [] arr = { names, values }; 1596 1597 namesAndValues = new SoftReference <Object >(arr); 1598 1599 return arr; 1600 } 1601 1602 1607 public static String keyToString(KeyStroke stroke) { 1608 StringBuffer sb = new StringBuffer (); 1609 1610 if (addModifiers(sb, stroke.getModifiers())) { 1612 sb.append('-'); 1613 } 1614 1615 HashMap [] namesAndValues = initNameAndValues(); 1616 1617 String c = (String ) namesAndValues[1].get(new Integer (stroke.getKeyCode())); 1618 1619 if (c == null) { 1620 sb.append(stroke.getKeyChar()); 1621 } else { 1622 sb.append(c); 1623 } 1624 1625 return sb.toString(); 1626 } 1627 1628 1667 public static KeyStroke stringToKey(String s) { 1668 StringTokenizer st = new StringTokenizer (s.toUpperCase(Locale.ENGLISH), "-", true); 1670 int needed = 0; 1671 1672 HashMap names = initNameAndValues()[0]; 1673 1674 int lastModif = -1; 1675 1676 try { 1677 for (;;) { 1678 String el = st.nextToken(); 1679 1680 if (el.equals("-")) { 1683 if (lastModif != -1) { 1684 needed |= lastModif; 1685 lastModif = -1; 1686 } 1687 1688 continue; 1689 } 1690 1691 if (st.hasMoreElements()) { 1693 lastModif = readModifiers(el); 1695 } else { 1696 Integer i = (Integer ) names.get(el); 1698 boolean wildcard = (needed & CTRL_WILDCARD_MASK) != 0; 1699 1700 needed = needed & ~CTRL_WILDCARD_MASK; 1703 1704 boolean macAlt = (needed & ALT_WILDCARD_MASK) != 0; 1705 needed = needed & ~ALT_WILDCARD_MASK; 1706 1707 if (i != null) { 1708 if (wildcard) { 1710 needed |= Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); 1711 1712 if (isMac()) { 1713 if (!usableKeyOnMac(i.intValue(), needed)) { 1714 needed &= ~Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); 1715 needed |= KeyEvent.CTRL_MASK; 1716 } 1717 } 1718 } 1719 1720 if (macAlt) { 1721 if (getOperatingSystem() == OS_MAC) { 1722 needed |= KeyEvent.CTRL_MASK; 1723 } else { 1724 needed |= KeyEvent.ALT_MASK; 1725 } 1726 } 1727 1728 return KeyStroke.getKeyStroke(i.intValue(), needed); 1729 } else { 1730 return null; 1731 } 1732 } 1733 } 1734 } catch (NoSuchElementException ex) { 1735 return null; 1736 } 1737 } 1738 1739 private static final boolean usableKeyOnMac(int key, int mask) { 1740 if (key == KeyEvent.VK_Q) { 1742 return false; 1743 } 1744 1745 boolean isMeta = ((mask & KeyEvent.META_MASK) != 0) || ((mask & KeyEvent.CTRL_DOWN_MASK) != 0); 1746 1747 boolean isAlt = ((mask & KeyEvent.ALT_MASK) != 0) || ((mask & KeyEvent.ALT_DOWN_MASK) != 0); 1748 1749 boolean isOnlyMeta = isMeta && ((mask & ~(KeyEvent.META_DOWN_MASK | KeyEvent.META_MASK)) == 0); 1750 1751 if (isOnlyMeta) { 1754 return (key != KeyEvent.VK_H) && (key != KeyEvent.VK_SPACE) && (key != KeyEvent.VK_TAB); 1755 } else if ((key == KeyEvent.VK_D) && isMeta && isAlt) { 1756 return false; 1757 } else { 1758 return true; 1759 } 1760 } 1761 1762 1767 public static KeyStroke [] stringToKeys(String s) { 1768 StringTokenizer st = new StringTokenizer (s.toUpperCase(Locale.ENGLISH), " "); ArrayList <KeyStroke > arr = new ArrayList <KeyStroke >(); 1770 1771 while (st.hasMoreElements()) { 1772 s = st.nextToken(); 1773 1774 KeyStroke k = stringToKey(s); 1775 1776 if (k == null) { 1777 return null; 1778 } 1779 1780 arr.add(k); 1781 } 1782 1783 return arr.toArray(new KeyStroke [arr.size()]); 1784 } 1785 1786 1791 private static boolean addModifiers(StringBuffer buf, int modif) { 1792 boolean b = false; 1793 1794 if ((modif & KeyEvent.CTRL_MASK) != 0) { 1795 buf.append("C"); b = true; 1797 } 1798 1799 if ((modif & KeyEvent.ALT_MASK) != 0) { 1800 buf.append("A"); b = true; 1802 } 1803 1804 if ((modif & KeyEvent.SHIFT_MASK) != 0) { 1805 buf.append("S"); b = true; 1807 } 1808 1809 if ((modif & KeyEvent.META_MASK) != 0) { 1810 buf.append("M"); b = true; 1812 } 1813 1814 if ((modif & CTRL_WILDCARD_MASK) != 0) { 1815 buf.append("D"); 1816 b = true; 1817 } 1818 1819 if ((modif & ALT_WILDCARD_MASK) != 0) { 1820 buf.append("O"); 1821 b = true; 1822 } 1823 1824 return b; 1825 } 1826 1827 1832 private static int readModifiers(String s) throws NoSuchElementException { 1833 int m = 0; 1834 1835 for (int i = 0; i < s.length(); i++) { 1836 switch (s.charAt(i)) { 1837 case 'C': 1838 m |= KeyEvent.CTRL_MASK; 1839 1840 break; 1841 1842 case 'A': 1843 m |= KeyEvent.ALT_MASK; 1844 1845 break; 1846 1847 case 'M': 1848 m |= KeyEvent.META_MASK; 1849 1850 break; 1851 1852 case 'S': 1853 m |= KeyEvent.SHIFT_MASK; 1854 1855 break; 1856 1857 case 'D': 1858 m |= CTRL_WILDCARD_MASK; 1859 1860 break; 1861 1862 case 'O': 1863 m |= ALT_WILDCARD_MASK; 1864 1865 break; 1866 1867 default: 1868 throw new NoSuchElementException (s); 1869 } 1870 } 1871 1872 return m; 1873 } 1874 1875 1883 private static GraphicsConfiguration getCurrentGraphicsConfiguration() { 1884 Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); 1885 if (focusOwner != null) { 1886 Window w = SwingUtilities.getWindowAncestor(focusOwner); 1887 if (w != null) { 1888 return w.getGraphicsConfiguration(); 1889 } 1890 } 1891 1892 return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); 1893 } 1894 1895 1906 public static Rectangle getUsableScreenBounds() { 1907 return getUsableScreenBounds(getCurrentGraphicsConfiguration()); 1908 } 1909 1910 1920 public static Rectangle getUsableScreenBounds(GraphicsConfiguration gconf) { 1921 if (gconf == null) { 1922 gconf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); 1923 } 1924 1925 Rectangle bounds = new Rectangle (gconf.getBounds()); 1926 1927 String str; 1928 1929 str = System.getProperty("netbeans.screen.insets"); 1931 if (str != null) { 1932 StringTokenizer st = new StringTokenizer (str, ", "); 1934 if (st.countTokens() == 4) { 1935 try { 1936 bounds.y = Integer.parseInt(st.nextToken()); 1937 bounds.x = Integer.parseInt(st.nextToken()); 1938 bounds.height -= (bounds.y + Integer.parseInt(st.nextToken())); 1939 bounds.width -= (bounds.x + Integer.parseInt(st.nextToken())); 1940 } catch (NumberFormatException ex) { 1941 Logger.getAnonymousLogger().log(Level.WARNING, null, ex); 1942 } 1943 } 1944 1945 return bounds; 1946 } 1947 1948 str = System.getProperty("netbeans.taskbar.height"); 1950 if (str != null) { 1951 bounds.height -= Integer.getInteger(str, 0).intValue(); 1952 1953 return bounds; 1954 } 1955 1956 try { 1957 Toolkit toolkit = Toolkit.getDefaultToolkit(); 1958 Insets insets = toolkit.getScreenInsets(gconf); 1959 bounds.y += insets.top; 1960 bounds.x += insets.left; 1961 bounds.height -= (insets.top + insets.bottom); 1962 bounds.width -= (insets.left + insets.right); 1963 } catch (Exception ex) { 1964 Logger.getAnonymousLogger().log(Level.WARNING, null, ex); 1965 } 1966 1967 return bounds; 1968 } 1969 1970 1979 public static Rectangle findCenterBounds(Dimension componentSize) { 1980 return findCenterBounds(getCurrentGraphicsConfiguration(), componentSize); 1981 } 1982 1983 1991 private static Rectangle findCenterBounds(GraphicsConfiguration gconf, Dimension componentSize) { 1992 if (gconf == null) { 1993 gconf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); 1994 } 1995 1996 Rectangle bounds = gconf.getBounds(); 1997 1998 return new Rectangle ( 1999 bounds.x + ((bounds.width - componentSize.width) / 2), 2000 bounds.y + ((bounds.height - componentSize.height) / 2), componentSize.width, componentSize.height 2001 ); 2002 } 2003 2004 2012 @Deprecated 2013 public static final Dimension getScreenSize() { 2014 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 2015 2016 if (isWindows() && !Boolean.getBoolean("netbeans.no.taskbar")) { 2017 screenSize.height -= TYPICAL_WINDOWS_TASKBAR_HEIGHT; 2018 } else if (isMac()) { 2019 screenSize.height -= TYPICAL_MACOSX_MENU_HEIGHT; 2020 } 2021 2022 return screenSize; 2023 } 2024 2025 2030 @Deprecated 2031 public static final int showJFileChooser( 2032 javax.swing.JFileChooser chooser, java.awt.Component parent, java.lang.String approveButtonText 2033 ) { 2034 if (approveButtonText != null) { 2035 chooser.setApproveButtonText(approveButtonText); 2036 chooser.setDialogType(javax.swing.JFileChooser.CUSTOM_DIALOG); 2037 } 2038 2039 Frame frame = null; 2040 Dialog parentDlg = null; 2041 2042 if (parent instanceof Dialog ) { 2043 parentDlg = (Dialog ) parent; 2044 } else { 2045 frame = (parent instanceof java.awt.Frame ) ? (Frame ) parent 2046 : (Frame ) javax.swing.SwingUtilities.getAncestorOfClass( 2047 Frame .class, parent 2048 ); 2049 } 2050 2051 String title = chooser.getDialogTitle(); 2052 2053 if (title == null) { 2054 title = chooser.getUI().getDialogTitle(chooser); 2055 } 2056 2057 final javax.swing.JDialog dialog; 2058 2059 if (parentDlg != null) { 2060 dialog = new javax.swing.JDialog (parentDlg, title, true); 2061 } else { 2062 dialog = new javax.swing.JDialog (frame, title, true); 2063 } 2064 2065 dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); 2066 2067 Container contentPane = dialog.getContentPane(); 2068 contentPane.setLayout(new BorderLayout ()); 2069 contentPane.add(chooser, BorderLayout.CENTER); 2070 2071 dialog.pack(); 2072 dialog.setBounds(findCenterBounds(parent.getGraphicsConfiguration(), dialog.getSize())); 2073 2074 chooser.rescanCurrentDirectory(); 2075 2076 final int[] retValue = new int[] { javax.swing.JFileChooser.CANCEL_OPTION }; 2077 2078 java.awt.event.ActionListener l = new java.awt.event.ActionListener () { 2079 public void actionPerformed(java.awt.event.ActionEvent ev) { 2080 if (ev.getActionCommand() == javax.swing.JFileChooser.APPROVE_SELECTION) { 2081 retValue[0] = javax.swing.JFileChooser.APPROVE_OPTION; 2082 } 2083 2084 dialog.setVisible(false); 2085 dialog.dispose(); 2086 } 2087 }; 2088 2089 chooser.addActionListener(l); 2090 2091 dialog.show(); 2092 2093 return retValue[0]; 2094 } 2095 2096 2109 @SuppressWarnings ("unchecked") @Deprecated 2111 public static List partialSort(List l, Comparator c, boolean stable) 2112 throws UnorderableException { 2113 Map deps = new HashMap (); int size = l.size(); 2117 2118 for (int i = 0; i < size; i++) { 2120 for (int j = i + 1; j < size; j++) { 2121 int cmp = c.compare(l.get(i), l.get(j)); 2122 2123 if (cmp != 0) { 2124 Object earlier = l.get((cmp < 0) ? i : j); 2125 Object later = l.get((cmp > 0) ? i : j); 2126 Set s = (Set ) deps.get(later); 2127 2128 if (s == null) { 2129 deps.put(later, s = new HashSet ()); 2130 } 2131 2132 s.add(earlier); 2133 } 2134 } 2135 } 2136 2137 List left = new LinkedList (l); 2139 List sorted = new ArrayList (size); 2140 2141 while (left.size() > 0) { 2142 boolean stillGoing = false; 2143 Iterator it = left.iterator(); 2144 2145 while (it.hasNext()) { 2146 Object elt = it.next(); 2147 Set eltDeps = (Set ) deps.get(elt); 2148 2149 if ((eltDeps == null) || (eltDeps.size() == 0)) { 2150 it.remove(); 2152 stillGoing = true; 2153 sorted.add(elt); 2154 2155 Iterator it2 = left.iterator(); 2158 2159 while (it2.hasNext()) { 2160 Object elt2 = it2.next(); 2161 Set eltDeps2 = (Set ) deps.get(elt2); 2162 2163 if (eltDeps2 != null) { 2164 eltDeps2.remove(elt); 2165 } 2166 } 2167 2168 if (stable) { 2169 break; 2170 } 2171 } 2172 } 2173 2174 if (!stillGoing) { 2175 it = deps.entrySet().iterator(); 2177 2178 while (it.hasNext()) { 2179 Map.Entry me = (Map.Entry ) it.next(); 2180 2181 if (!left.contains(me.getKey())) { 2182 it.remove(); 2183 } else { 2184 Set s = (Set ) me.getValue(); 2185 Iterator it2 = s.iterator(); 2186 2187 while (it2.hasNext()) { 2188 if (!left.contains(it2.next())) { 2189 it2.remove(); 2190 } 2191 } 2192 2193 if (s.isEmpty()) { 2194 it.remove(); 2195 } 2196 } 2197 } 2198 2199 throw new UnorderableException(left, deps); 2200 } 2201 } 2202 2203 return sorted; 2204 } 2205 2206 2232 public static <T> List <T> topologicalSort(Collection <T> c, Map <? super T, ? extends Collection <? extends T>> edges) 2233 throws TopologicalSortException { 2234 Map <T,Boolean > finished = new HashMap <T,Boolean >(); 2235 List <T> r = new ArrayList <T>(Math.max(c.size(), 1)); 2236 List <T> cRev = new ArrayList <T>(c); 2237 Collections.reverse(cRev); 2238 2239 Iterator <T> it = cRev.iterator(); 2240 2241 while (it.hasNext()) { 2242 List <T> cycle = visit(it.next(), edges, finished, r); 2243 2244 if (cycle != null) { 2245 throw new TopologicalSortException(cRev, edges); 2246 } 2247 } 2248 2249 Collections.reverse(r); 2250 2251 return r; 2252 } 2253 2254 2264 static <T> List <T> visit( 2265 T node, 2266 Map <? super T, ? extends Collection <? extends T>> edges, 2267 Map <T,Boolean > finished, 2268 List <T> r 2269 ) { 2270 Boolean b = finished.get(node); 2271 2272 if (b != null) { 2274 if (b.booleanValue()) { 2275 return null; 2276 } 2277 2278 ArrayList <T> cycle = new ArrayList <T>(); 2279 cycle.add(node); 2280 finished.put(node, null); 2281 2282 return cycle; 2283 } 2284 2285 Collection <? extends T> e = edges.get(node); 2286 2287 if (e != null) { 2288 finished.put(node, Boolean.FALSE); 2289 2290 Iterator <? extends T> it = e.iterator(); 2291 2292 while (it.hasNext()) { 2293 List <T> cycle = visit(it.next(), edges, finished, r); 2294 2295 if (cycle != null) { 2296 if (cycle instanceof ArrayList ) { 2297 if (Boolean.FALSE == finished.get(node)) { 2300 cycle.add(node); 2302 } else { 2303 Collections.reverse(cycle); 2306 2307 cycle = Collections.unmodifiableList(cycle); 2309 } 2310 } 2311 2312 finished.put(node, Boolean.TRUE); 2314 2315 return cycle; 2317 } 2318 } 2319 } 2320 2321 finished.put(node, Boolean.TRUE); 2322 r.add(node); 2323 2324 return null; 2325 } 2326 2327 2374 public static String translate(final String className) { 2375 checkMapping(); 2376 2377 RE exp; 2378 2379 synchronized (TRANS_LOCK) { 2380 exp = transExp; 2381 } 2382 2383 if (exp == null) { 2384 return className; 2386 } 2387 2388 synchronized (exp) { 2389 return exp.convert(className); 2391 } 2392 } 2393 2394 2397 private static void checkMapping() { 2398 if (transLoader == TRANS_LOCK) { 2400 return; 2402 } 2403 2404 ClassLoader current = Lookup.getDefault().lookup(ClassLoader .class); 2405 2406 if (current == null) { 2407 current = ClassLoader.getSystemClassLoader(); 2408 } 2409 2410 if (transLoader == current) { 2411 return; 2413 } 2414 2415 initForLoader(current, current); 2416 } 2417 2418 2422 static void initForLoader(ClassLoader current, Object set) { 2423 if (set == null) { 2424 set = TRANS_LOCK; 2425 } 2426 2427 Enumeration en; 2428 2429 try { 2430 en = current.getResources("META-INF/netbeans/translate.names"); 2431 } catch (IOException ex) { 2432 Logger.getAnonymousLogger().log(Level.WARNING, null, ex); 2433 en = null; 2434 } 2435 2436 if ((en == null) || !en.hasMoreElements()) { 2437 synchronized (TRANS_LOCK) { 2438 transLoader = set; 2439 transExp = null; 2440 } 2441 2442 return; 2443 } 2444 2445 RE re = null; 2452 2453 re = new RE13(); 2465 2466 TreeSet <String []> list = new TreeSet <String []>( 2468 new Comparator <String []>() { 2469 public int compare(String [] o1, String [] o2) { 2470 String s1 = o1[0]; 2471 String s2 = o2[0]; 2472 2473 int i1 = s1.length(); 2474 int i2 = s2.length(); 2475 2476 if (i1 != i2) { 2477 return i2 - i1; 2478 } 2479 2480 return s2.compareTo(s1); 2481 } 2482 } 2483 ); 2484 2485 while (en.hasMoreElements()) { 2486 URL u = (URL ) en.nextElement(); 2487 2488 try { 2489 BufferedReader reader = new BufferedReader ( 2490 new InputStreamReader (u.openStream(), "UTF8") ); 2492 loadTranslationFile(re, reader, list); 2493 reader.close(); 2494 } catch (IOException ex) { 2495 Logger.getAnonymousLogger().log(Level.WARNING, "Problematic file: " + u); 2496 Logger.getAnonymousLogger().log(Level.WARNING, null, ex); 2497 } 2498 } 2499 2500 String [] arr = new String [list.size()]; 2505 String [] pattern = new String [arr.length]; 2506 2507 int i = 0; 2508 Iterator it = list.iterator(); 2509 2510 while (it.hasNext()) { 2511 String [] pair = (String []) it.next(); 2512 arr[i] = pair[1].intern(); pattern[i] = pair[0]; i++; 2515 } 2516 2517 synchronized (TRANS_LOCK) { 2518 if (arr.length == 0) { 2520 transExp = null; 2521 } else { 2522 transExp = re; 2523 transExp.init(pattern, arr); 2524 } 2525 2526 transLoader = set; 2527 } 2528 } 2529 2530 2535 private static void loadTranslationFile(RE re, BufferedReader reader, Set <String []> results) 2536 throws IOException { 2537 for (;;) { 2538 String line = reader.readLine(); 2539 2540 if (line == null) { 2541 break; 2542 } 2543 2544 if ((line.length() == 0) || line.startsWith("#")) { 2546 continue; 2547 } 2548 2549 String [] pair = re.readPair(line); 2550 2551 if (pair == null) { 2552 throw new java.io.InvalidObjectException ("Line is invalid: " + line); 2553 } 2554 2555 results.add(pair); 2556 } 2557 } 2558 2559 2570 public static final Image mergeImages(Image image1, Image image2, int x, int y) { 2571 if (image1 == null) { 2572 throw new NullPointerException (); 2573 } 2574 2575 if (image2 == null) { 2576 throw new NullPointerException (); 2577 } 2578 2579 return IconManager.mergeImages(image1, image2, x, y); 2580 } 2581 2582 2588 public static final Image loadImage(String resourceID) { 2589 return IconManager.getIcon(resourceID, false); 2590 } 2591 2592 2598 public static final Image icon2Image(Icon icon) { 2599 if (icon instanceof ImageIcon ) { 2600 return ((ImageIcon ) icon).getImage(); 2601 } else { 2602 BufferedImage bImage = new BufferedImage (icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); 2603 Graphics g = bImage.getGraphics(); 2604 icon.paintIcon(new JLabel (), g, 0, 0); 2605 g.dispose(); 2606 return bImage; 2607 } 2608 } 2609 2610 2624 public static JPopupMenu actionsToPopup(Action [] actions, Lookup context) { 2625 Set <Action > counted = new HashSet <Action >(); 2627 List <Component > components = new ArrayList <Component >(); 2629 2630 for (Action action : actions) { 2631 if (action != null && counted.add(action)) { 2632 if (action instanceof ContextAwareAction) { 2634 Action contextAwareAction = ((ContextAwareAction) action).createContextAwareInstance(context); 2635 if (contextAwareAction == null) { 2636 Logger.getLogger(Utilities.class.getName()).warning( 2637 "ContextAwareAction.createContextAwareInstance(context) returns null. That is illegal!" + " action=" + action + ", context=" + context); } else { 2640 action = contextAwareAction; 2641 } 2642 } 2643 2644 JMenuItem item; 2645 if (action instanceof Presenter.Popup) { 2646 item = ((Presenter.Popup) action).getPopupPresenter(); 2647 if (item == null) { 2648 Logger.getLogger(Utilities.class.getName()).warning( 2649 "findContextMenuImpl, getPopupPresenter returning null for " + action); continue; 2651 } 2652 } else { 2653 item = AWTBridge.getDefault().createPopupPresenter(action); 2655 } 2656 2657 for (Component c : AWTBridge.getDefault().convertComponents(item)) { 2658 if (c instanceof JSeparator ) { 2659 components.add(null); 2660 } else { 2661 components.add(c); 2662 } 2663 } 2664 } else { 2665 components.add(null); 2666 } 2667 } 2668 2669 JPopupMenu menu = AWTBridge.getDefault().createEmptyPopup(); 2671 boolean nonempty = false; boolean pendingSep = false; for (Component c : components) { 2674 if (c == null) { 2675 pendingSep = nonempty; 2676 } else { 2677 nonempty = true; 2678 if (pendingSep) { 2679 pendingSep = false; 2680 menu.addSeparator(); 2681 } 2682 menu.add(c); 2683 } 2684 } 2685 return menu; 2686 } 2687 2688 2705 public static javax.swing.JPopupMenu actionsToPopup(Action [] actions, java.awt.Component component) { 2706 Lookup lookup = null; 2707 2708 for (Component c = component; c != null; c = c.getParent()) { 2709 if (c instanceof Lookup.Provider) { 2710 lookup = ((Lookup.Provider) c).getLookup(); 2711 2712 if (lookup != null) { 2713 break; 2714 } 2715 } 2716 } 2717 2718 if (lookup == null) { 2719 UtilitiesCompositeActionMap map = new UtilitiesCompositeActionMap(component); 2723 lookup = org.openide.util.lookup.Lookups.singleton(map); 2724 } 2725 2726 return actionsToPopup(actions, lookup); 2727 } 2728 2729 2738 public static Lookup actionsGlobalContext() { 2739 synchronized (ContextGlobalProvider.class) { 2740 if (global != null) { 2741 return global; 2742 } 2743 } 2744 2745 ContextGlobalProvider p = Lookup.getDefault().lookup(ContextGlobalProvider.class); 2746 Lookup l = (p == null) ? Lookup.EMPTY : p.createGlobalContext(); 2747 2748 synchronized (ContextGlobalProvider.class) { 2749 if (global == null) { 2750 global = l; 2751 } 2752 2753 return global; 2754 } 2755 } 2756 2757 2761 2772 public static final Image loadImage(String resource, boolean localized) { 2773 return IconManager.getIcon(resource, localized); 2774 } 2775 2776 2805 public static final Cursor createProgressCursor(Component component) { 2806 if (component == null) { 2808 throw new NullPointerException ("Given component is null"); } 2810 2811 Image image = null; 2812 2813 if (isMac()) { 2815 image = loadImage("org/openide/util/progress-cursor-mac.gif"); } else if (isUnix()) { 2817 image = loadImage("org/openide/util/progress-cursor-motif.gif"); } 2819 else { 2821 image = loadImage("org/openide/util/progress-cursor-win.gif"); } 2823 2824 return createCustomCursor(component, image, "PROGRESS_CURSOR"); } 2826 2827 public static Cursor createCustomCursor(Component component, Image icon, String name) { 2829 Toolkit t = component.getToolkit(); 2830 Dimension d = t.getBestCursorSize(16, 16); 2831 Image i = icon; 2832 2833 if (d.width != icon.getWidth(null)) { 2834 if (((d.width) == 0) && (d.height == 0)) { 2835 return Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); 2837 } 2838 2839 Image empty = IconManager.createBufferedImage(d.width, d.height); 2841 i = Utilities.mergeImages(icon, empty, 0, 0); 2842 } 2843 2844 return t.createCustomCursor(i, new Point (1, 1), name); 2845 } 2846 2847 2865 public static final void attachInitJob(Component comp4Init, AsyncGUIJob initJob) { 2866 new AsyncInitSupport(comp4Init, initJob); 2867 } 2868 2869 2880 @Deprecated 2881 public static URL toURL(File f) throws MalformedURLException { 2882 if (f == null) { 2883 throw new NullPointerException (); 2884 } 2885 2886 if (!f.isAbsolute()) { 2887 throw new IllegalArgumentException ("Relative path: " + f); } 2889 2890 URI uri = f.toURI(); 2891 2892 return uri.toURL(); 2893 } 2894 2895 2909 @Deprecated 2910 public static File toFile(URL u) { 2911 if (u == null) { 2912 throw new NullPointerException (); 2913 } 2914 2915 try { 2916 URI uri = new URI (u.toExternalForm()); 2917 2918 return new File (uri); 2919 } catch (URISyntaxException use) { 2920 return null; 2922 } catch (IllegalArgumentException iae) { 2923 return null; 2925 } 2926 } 2927 2928 2936 static interface RE { 2937 public void init(String [] original, String [] newversion); 2938 2939 public String convert(String pattern); 2940 2941 2943 public String [] readPair(String line); 2944 } 2945 2946 2950 @Deprecated 2951 public static class UnorderableException extends RuntimeException { 2952 static final long serialVersionUID = 6749951134051806661L; 2953 private Collection unorderable; 2954 private Map deps; 2955 2956 2962 public UnorderableException(Collection unorderable, Map deps) { 2963 super( 2964 ); this.unorderable = unorderable; 2966 this.deps = deps; 2967 } 2968 2969 2976 public UnorderableException(String message, Collection unorderable, Map deps) { 2977 super(message); 2978 this.unorderable = unorderable; 2979 this.deps = deps; 2980 } 2981 2982 2986 public Collection getUnorderable() { 2987 return unorderable; 2988 } 2989 2990 2994 public Map getDeps() { 2995 return deps; 2996 } 2997 } 2998 2999 3001 private static final class ActiveQueue extends ReferenceQueue <Object > implements Runnable { 3002 3003 private static final Logger LOGGER = Logger.getLogger(ActiveQueue.class.getName().replace('$', '.')); 3004 3005 3006 private int count; 3007 private boolean deprecated; 3008 3009 public ActiveQueue(boolean deprecated) { 3010 this.deprecated = deprecated; 3011 } 3012 3013 public Reference <Object > poll() { 3014 throw new UnsupportedOperationException (); 3015 } 3016 3017 public Reference <Object > remove(long timeout) throws IllegalArgumentException , InterruptedException { 3018 throw new InterruptedException (); 3019 } 3020 3021 public Reference <Object > remove() throws InterruptedException { 3022 throw new InterruptedException (); 3023 } 3024 3025 public void run() { 3026 while (true) { 3027 try { 3028 Reference <?> ref = super.remove(0); 3029 LOGGER.finer("dequeued reference"); 3030 3031 if (!(ref instanceof Runnable )) { 3032 LOGGER.warning( 3033 "A reference not implementing runnable has been added to the Utilities.activeReferenceQueue(): " + 3034 ref.getClass() ); 3036 3037 continue; 3038 } 3039 3040 if (deprecated) { 3041 LOGGER.warning( 3042 "Utilities.ACTIVE_REFERENCE_QUEUE has been deprecated for " + ref.getClass() + 3043 " use Utilities.activeReferenceQueue" ); 3045 } 3046 3047 try { 3049 ((Runnable ) ref).run(); 3050 } catch (ThreadDeath td) { 3051 throw td; 3052 } catch (Throwable t) { 3053 LOGGER.log(Level.WARNING, null, t); 3056 } finally { 3057 ref = null; 3059 } 3060 } catch (InterruptedException ex) { 3061 LOGGER.log(Level.WARNING, null, ex); 3062 } 3063 3064 synchronized (this) { 3065 assert count > 0; 3066 count--; 3067 if (count == 0) { 3068 LOGGER.fine("stopping thread"); 3075 break; 3076 } 3077 } 3078 } 3079 } 3080 3081 synchronized void ping() { 3082 if (count == 0) { 3083 Thread t = new Thread (this, "Active Reference Queue Daemon"); t.setPriority(Thread.MIN_PRIORITY); 3085 t.setDaemon(true); t.start(); 3087 LOGGER.fine("starting thread"); 3090 } else { 3091 LOGGER.finer("enqueuing reference"); 3092 } 3093 count++; 3094 } 3095 3096 } 3097} 3098 | Popular Tags |