1871 lines · 69.6 KB · Java
RawDownload
    /*     * This method is to be used only for JComponent.getFontMetrics.     * In all other places to get FontMetrics we need to use     * JComponent.getFontMetrics.     *     */    public static FontMetrics getFontMetrics(JComponent c, Font font) {        FontRenderContext  frc = getFRCProperty(c);        if (frc == null) {            frc = DEFAULT_FRC;        }        return FontDesignMetrics.getMetrics(font, frc);    }      /* Get any FontRenderContext associated with a JComponent     * - may return null     */    private static FontRenderContext getFRCProperty(JComponent c) {        if (c != null) {            AATextInfo info =                (AATextInfo)c.getClientProperty(AA_TEXT_PROPERTY_KEY);            if (info != null) {                return info.frc;            }        }        return null;    }     /*     * returns true if the Graphics is print Graphics     * false otherwise     */    static boolean isPrinting(Graphics g) {        return (g instanceof PrinterGraphics || g instanceof PrintGraphics);    }     /**     * Determines whether the SelectedTextColor should be used for painting text     * foreground for the specified highlight.     *     * Returns true only if the highlight painter for the specified highlight     * is the swing painter (whether inner class of javax.swing.text.DefaultHighlighter     * or com.sun.java.swing.plaf.windows.WindowsTextUI) and its background color     * is null or equals to the selection color of the text component.     *     * This is a hack for fixing both bugs 4761990 and 5003294     */    public static boolean useSelectedTextColor(Highlighter.Highlight h, JTextComponent c) {        Highlighter.HighlightPainter painter = h.getPainter();        String painterClass = painter.getClass().getName();        if (painterClass.indexOf("javax.swing.text.DefaultHighlighter") != 0 &&                painterClass.indexOf("com.sun.java.swing.plaf.windows.WindowsTextUI") != 0) {            return false;        }        try {            DefaultHighlighter.DefaultHighlightPainter defPainter =                    (DefaultHighlighter.DefaultHighlightPainter) painter;            if (defPainter.getColor() != null &&                    !defPainter.getColor().equals(c.getSelectionColor())) {                return false;            }        } catch (ClassCastException e) {            return false;        }        return true;    }     /**     * LSBCacheEntry is used to cache the left side bearing (lsb) for     * a particular <code>Font</code> and <code>FontRenderContext</code>.     * This only caches characters that fall in the range     * <code>MIN_CHAR_INDEX</code> to <code>MAX_CHAR_INDEX</code>.     */    private static class LSBCacheEntry {        // Used to indicate a particular entry in lsb has not been set.        private static final byte UNSET = Byte.MAX_VALUE;        // Used in creating a GlyphVector to get the lsb        private static final char[] oneChar = new char[1];         private byte[] lsbCache;        private Font font;        private FontRenderContext frc;          public LSBCacheEntry(FontRenderContext frc, Font font) {            lsbCache = new byte[MAX_CHAR_INDEX - MIN_CHAR_INDEX];            reset(frc, font);         }         public void reset(FontRenderContext frc, Font font) {            this.font = font;            this.frc = frc;            for (int counter = lsbCache.length - 1; counter >= 0; counter--) {                lsbCache[counter] = UNSET;            }        }         public int getLeftSideBearing(char aChar) {            int index = aChar - MIN_CHAR_INDEX;            assert (index >= 0 && index < (MAX_CHAR_INDEX - MIN_CHAR_INDEX));            byte lsb = lsbCache[index];            if (lsb == UNSET) {                oneChar[0] = aChar;                GlyphVector gv = font.createGlyphVector(frc, oneChar);                lsb = (byte) gv.getGlyphPixelBounds(0, frc, 0f, 0f).x;                if (lsb < 0) {                    /* HRGB/HBGR LCD glyph images will always have a pixel                     * on the left used in colour fringe reduction.                     * Text rendering positions this correctly but here                     * we are using the glyph image to adjust that position                     * so must account for it.                     */                    Object aaHint = frc.getAntiAliasingHint();                    if (aaHint == VALUE_TEXT_ANTIALIAS_LCD_HRGB ||                            aaHint == VALUE_TEXT_ANTIALIAS_LCD_HBGR) {                        lsb++;                    }                }                lsbCache[index] = lsb;            }            return lsb;          }         public boolean equals(Object entry) {            if (entry == this) {                return true;            }            if (!(entry instanceof LSBCacheEntry)) {                return false;            }            LSBCacheEntry oEntry = (LSBCacheEntry) entry;            return (font.equals(oEntry.font) &&                    frc.equals(oEntry.frc));        }         public int hashCode() {            int result = 17;            if (font != null) {                result = 37 * result + font.hashCode();            }            if (frc != null) {                result = 37 * result + frc.hashCode();            }            return result;        }    }     /*     * here goes the fix for 4856343 [Problem with applet interaction     * with system selection clipboard]     *     * NOTE. In case isTrustedContext() no checking     * are to be performed     */     /**    * checks the security permissions for accessing system clipboard    *    * for untrusted context (see isTrustedContext) checks the    * permissions for the current event being handled    *    */   public static boolean canAccessSystemClipboard() {       boolean canAccess = false;       if (!GraphicsEnvironment.isHeadless()) {           SecurityManager sm = System.getSecurityManager();           if (sm == null) {               canAccess = true;           } else {               try {                   sm.checkSystemClipboardAccess();                   canAccess = true;               } catch (SecurityException e) {               }               if (canAccess && ! isTrustedContext()) {                   canAccess = canCurrentEventAccessSystemClipboard(true);               }           }       }       return canAccess;   }    /**    * Returns true if EventQueue.getCurrentEvent() has the permissions to     * access the system clipboard     */    public static boolean canCurrentEventAccessSystemClipboard() {        return  isTrustedContext()            || canCurrentEventAccessSystemClipboard(false);    }     /**     * Returns true if the given event has permissions to access the     * system clipboard     *     * @param e AWTEvent to check     */    public static boolean canEventAccessSystemClipboard(AWTEvent e) {        return isTrustedContext()            || canEventAccessSystemClipboard(e, false);    }     /**     * returns canAccessSystemClipboard field from InputEvent     *     * @param ie InputEvent to get the field from     */    private static synchronized boolean inputEvent_canAccessSystemClipboard(InputEvent ie) {        if (inputEvent_CanAccessSystemClipboard_Field == null) {            inputEvent_CanAccessSystemClipboard_Field =                AccessController.doPrivileged(                    new java.security.PrivilegedAction<Field>() {                        public Field run() {                            try {                                Field field = InputEvent.class.                                    getDeclaredField("canAccessSystemClipboard");                                field.setAccessible(true);                                return field;                            } catch (SecurityException e) {                            } catch (NoSuchFieldException e) {                            }                            return null;                        }                    });        }        if (inputEvent_CanAccessSystemClipboard_Field == null) {            return false;        }        boolean ret = false;        try {            ret = inputEvent_CanAccessSystemClipboard_Field.                getBoolean(ie);        } catch(IllegalAccessException e) {        }        return ret;    }     /**     * Returns true if the given event is corrent gesture for     * accessing clipboard     *     * @param ie InputEvent to check     */     private static boolean isAccessClipboardGesture(InputEvent ie) {        boolean allowedGesture = false;        if (ie instanceof KeyEvent) { //we can validate only keyboard gestures            KeyEvent ke = (KeyEvent)ie;            int keyCode = ke.getKeyCode();            int keyModifiers = ke.getModifiers();            switch(keyCode) {            case KeyEvent.VK_C:            case KeyEvent.VK_V:            case KeyEvent.VK_X:                allowedGesture = (keyModifiers == InputEvent.CTRL_MASK);                break;            case KeyEvent.VK_INSERT:                allowedGesture = (keyModifiers == InputEvent.CTRL_MASK ||                                  keyModifiers == InputEvent.SHIFT_MASK);                break;            case KeyEvent.VK_COPY:            case KeyEvent.VK_PASTE:            case KeyEvent.VK_CUT:                allowedGesture = true;                break;            case KeyEvent.VK_DELETE:                allowedGesture = ( keyModifiers == InputEvent.SHIFT_MASK);                break;            }        }        return allowedGesture;    }     /**     * Returns true if e has the permissions to     * access the system clipboard and if it is allowed gesture (if     * checkGesture is true)     *     * @param e AWTEvent to check     * @param checkGesture boolean     */    private static boolean canEventAccessSystemClipboard(AWTEvent e,                                                        boolean checkGesture) {        if (EventQueue.isDispatchThread()) {            /*             * Checking event permissions makes sense only for event             * dispathing thread             */            if (e instanceof InputEvent                && (! checkGesture || isAccessClipboardGesture((InputEvent)e))) {                return inputEvent_canAccessSystemClipboard((InputEvent)e);            } else {                return false;            }        } else {            return true;        }    }     /**     * Returns true if EventQueue.getCurrentEvent() has the permissions to     * access the system clipboard and if it is allowed gesture (if     * checkGesture true)     *     * @param checkGesture boolean     */    private static boolean canCurrentEventAccessSystemClipboard(boolean                                                               checkGesture) {        AWTEvent event = EventQueue.getCurrentEvent();        return canEventAccessSystemClipboard(event, checkGesture);    }     /**     * see RFE 5012841 [Per AppContect security permissions] for the     * details     *     */    private static boolean isTrustedContext() {        return (System.getSecurityManager() == null)            || (AppContext.getAppContext().                get(UntrustedClipboardAccess) == null);    }     public static String displayPropertiesToCSS(Font font, Color fg) {        StringBuffer rule = new StringBuffer("body {");        if (font != null) {            rule.append(" font-family: ");            rule.append(font.getFamily());            rule.append(" ; ");            rule.append(" font-size: ");            rule.append(font.getSize());            rule.append("pt ;");            if (font.isBold()) {                rule.append(" font-weight: 700 ; ");            }            if (font.isItalic()) {                rule.append(" font-style: italic ; ");            }        }        if (fg != null) {            rule.append(" color: #");            if (fg.getRed() < 16) {                rule.append('0');            }            rule.append(Integer.toHexString(fg.getRed()));            if (fg.getGreen() < 16) {                rule.append('0');            }            rule.append(Integer.toHexString(fg.getGreen()));            if (fg.getBlue() < 16) {                rule.append('0');            }            rule.append(Integer.toHexString(fg.getBlue()));            rule.append(" ; ");        }        rule.append(" }");        return rule.toString();    }     /**     * Utility method that creates a <code>UIDefaults.LazyValue</code> that     * creates an <code>ImageIcon</code> <code>UIResource</code> for the     * specified image file name. The image is loaded using     * <code>getResourceAsStream</code>, starting with a call to that method     * on the base class parameter. If it cannot be found, searching will     * continue through the base class' inheritance hierarchy, up to and     * including <code>rootClass</code>.     *     * @param baseClass the first class to use in searching for the resource     * @param rootClass an ancestor of <code>baseClass</code> to finish the     *                  search at     * @param imageFile the name of the file to be found     * @return a lazy value that creates the <code>ImageIcon</code>     *         <code>UIResource</code> for the image,     *         or null if it cannot be found     */    public static Object makeIcon(final Class<?> baseClass,                                  final Class<?> rootClass,                                  final String imageFile) {         return new UIDefaults.LazyValue() {            public Object createValue(UIDefaults table) {                /* Copy resource into a byte array.  This is                 * necessary because several browsers consider                 * Class.getResource a security risk because it                 * can be used to load additional classes.                 * Class.getResourceAsStream just returns raw                 * bytes, which we can convert to an image.                 */                byte[] buffer =                    java.security.AccessController.doPrivileged(                        new java.security.PrivilegedAction<byte[]>() {                    public byte[] run() {                        try {                            InputStream resource = null;                            Class<?> srchClass = baseClass;                             while (srchClass != null) {                                resource = srchClass.getResourceAsStream(imageFile);                                 if (resource != null || srchClass == rootClass) {                                    break;                                }                                 srchClass = srchClass.getSuperclass();                            }                             if (resource == null) {                                return null;                            }                             BufferedInputStream in =                                new BufferedInputStream(resource);                            ByteArrayOutputStream out =                                new ByteArrayOutputStream(1024);                            byte[] buffer = new byte[1024];                            int n;                            while ((n = in.read(buffer)) > 0) {                                out.write(buffer, 0, n);                            }                            in.close();                            out.flush();                            return out.toByteArray();                        } catch (IOException ioe) {                            System.err.println(ioe.toString());                        }                        return null;                    }                });                 if (buffer == null) {                    return null;                }                if (buffer.length == 0) {                    System.err.println("warning: " + imageFile +                                       " is zero-length");                    return null;                }                 return new ImageIconUIResource(buffer);            }        };    }     /* Used to help decide if AA text rendering should be used, so     * this local display test should be additionally qualified     * against whether we have XRender support on both ends of the wire,     * as with that support remote performance may be good enough to turn     * on by default. An additional complication there is XRender does not     * appear capable of performing gamma correction needed for LCD text.     */    public static boolean isLocalDisplay() {        boolean isLocal;        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();        if (ge instanceof SunGraphicsEnvironment) {            isLocal = ((SunGraphicsEnvironment) ge).isDisplayLocal();        } else {            isLocal = true;        }        return isLocal;    }     /**     * Returns an integer from the defaults table. If <code>key</code> does     * not map to a valid <code>Integer</code>, or can not be convered from     * a <code>String</code> to an integer, the value 0 is returned.     *     * @param key  an <code>Object</code> specifying the int.     * @return the int     */    public static int getUIDefaultsInt(Object key) {        return getUIDefaultsInt(key, 0);    }     /**     * Returns an integer from the defaults table that is appropriate     * for the given locale. If <code>key</code> does not map to a valid     * <code>Integer</code>, or can not be convered from a <code>String</code>     * to an integer, the value 0 is returned.     *     * @param key  an <code>Object</code> specifying the int. Returned value     *             is 0 if <code>key</code> is not available,     * @param l the <code>Locale</code> for which the int is desired     * @return the int     */    public static int getUIDefaultsInt(Object key, Locale l) {        return getUIDefaultsInt(key, l, 0);    }     /**     * Returns an integer from the defaults table. If <code>key</code> does     * not map to a valid <code>Integer</code>, or can not be convered from     * a <code>String</code> to an integer, <code>default</code> is     * returned.     *     * @param key  an <code>Object</code> specifying the int. Returned value     *             is 0 if <code>key</code> is not available,

Lines 1001–1500 of 1871. Previous lines