FontUtilities.java revision 11099:678faa7d1a6a
1239324Simp/*
2239324Simp * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
3239324Simp * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4239324Simp *
5239324Simp * This code is free software; you can redistribute it and/or modify it
6239324Simp * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package sun.font;
27
28import java.awt.Font;
29import java.io.BufferedReader;
30import java.io.File;
31import java.io.FileInputStream;
32import java.io.InputStreamReader;
33import java.lang.ref.SoftReference;
34import java.util.concurrent.ConcurrentHashMap;
35import java.security.AccessController;
36
37import java.security.PrivilegedAction;
38import javax.swing.plaf.FontUIResource;
39
40import sun.util.logging.PlatformLogger;
41
42/**
43 * A collection of utility methods.
44 */
45public final class FontUtilities {
46
47    public static boolean isSolaris;
48
49    public static boolean isLinux;
50
51    public static boolean isMacOSX;
52
53    public static boolean isSolaris8;
54
55    public static boolean isSolaris9;
56
57    public static boolean isOpenSolaris;
58
59    public static boolean useT2K;
60
61    public static boolean isWindows;
62
63    public static boolean isOpenJDK;
64
65    static final String LUCIDA_FILE_NAME = "LucidaSansRegular.ttf";
66
67    private static boolean debugFonts = false;
68    private static PlatformLogger logger = null;
69    private static boolean logging;
70
71    // This static initializer block figures out the OS constants.
72    static {
73
74        AccessController.doPrivileged(new PrivilegedAction<Object>() {
75            public Object run() {
76                String osName = System.getProperty("os.name", "unknownOS");
77                isSolaris = osName.startsWith("SunOS");
78
79                isLinux = osName.startsWith("Linux");
80
81                isMacOSX = osName.contains("OS X"); // TODO: MacOSX
82
83                String t2kStr = System.getProperty("sun.java2d.font.scaler");
84                if (t2kStr != null) {
85                    useT2K = "t2k".equals(t2kStr);
86                } else {
87                    useT2K = false;
88                }
89                if (isSolaris) {
90                    String version = System.getProperty("os.version", "0.0");
91                    isSolaris8 = version.startsWith("5.8");
92                    isSolaris9 = version.startsWith("5.9");
93                    float ver = Float.parseFloat(version);
94                    if (ver > 5.10f) {
95                        File f = new File("/etc/release");
96                        String line = null;
97                        try {
98                            FileInputStream fis = new FileInputStream(f);
99                            InputStreamReader isr = new InputStreamReader(
100                                                            fis, "ISO-8859-1");
101                            BufferedReader br = new BufferedReader(isr);
102                            line = br.readLine();
103                            fis.close();
104                        } catch (Exception ex) {
105                            // Nothing to do here.
106                        }
107                        if (line != null && line.indexOf("OpenSolaris") >= 0) {
108                            isOpenSolaris = true;
109                        } else {
110                            isOpenSolaris = false;
111                        }
112                    } else {
113                        isOpenSolaris = false;
114                    }
115                } else {
116                    isSolaris8 = false;
117                    isSolaris9 = false;
118                    isOpenSolaris = false;
119                }
120                isWindows = osName.startsWith("Windows");
121                String jreLibDirName = System.getProperty("java.home", "")
122                                                      + File.separator + "lib";
123                String jreFontDirName =
124                        jreLibDirName + File.separator + "fonts";
125                File lucidaFile = new File(jreFontDirName + File.separator
126                                           + LUCIDA_FILE_NAME);
127                isOpenJDK = !lucidaFile.exists();
128
129                String debugLevel =
130                    System.getProperty("sun.java2d.debugfonts");
131
132                if (debugLevel != null && !debugLevel.equals("false")) {
133                    debugFonts = true;
134                    logger = PlatformLogger.getLogger("sun.java2d");
135                    if (debugLevel.equals("warning")) {
136                        logger.setLevel(PlatformLogger.Level.WARNING);
137                    } else if (debugLevel.equals("severe")) {
138                        logger.setLevel(PlatformLogger.Level.SEVERE);
139                    }
140                }
141
142                if (debugFonts) {
143                    logger = PlatformLogger.getLogger("sun.java2d");
144                    logging = logger.isEnabled();
145                }
146
147                return null;
148            }
149        });
150    }
151
152    /**
153     * Referenced by code in the JDK which wants to test for the
154     * minimum char code for which layout may be required.
155     * Note that even basic latin text can benefit from ligatures,
156     * eg "ffi" but we presently apply those only if explicitly
157     * requested with TextAttribute.LIGATURES_ON.
158     * The value here indicates the lowest char code for which failing
159     * to invoke layout would prevent acceptable rendering.
160     */
161    public static final int MIN_LAYOUT_CHARCODE = 0x0300;
162
163    /**
164     * Referenced by code in the JDK which wants to test for the
165     * maximum char code for which layout may be required.
166     * Note this does not account for supplementary characters
167     * where the caller interprets 'layout' to mean any case where
168     * one 'char' (ie the java type char) does not map to one glyph
169     */
170    public static final int MAX_LAYOUT_CHARCODE = 0x206F;
171
172    /**
173     * Calls the private getFont2D() method in java.awt.Font objects.
174     *
175     * @param font the font object to call
176     *
177     * @return the Font2D object returned by Font.getFont2D()
178     */
179    public static Font2D getFont2D(Font font) {
180        return FontAccess.getFontAccess().getFont2D(font);
181    }
182
183    /**
184     * If there is anything in the text which triggers a case
185     * where char->glyph does not map 1:1 in straightforward
186     * left->right ordering, then this method returns true.
187     * Scripts which might require it but are not treated as such
188     * due to JDK implementations will not return true.
189     * ie a 'true' return is an indication of the treatment by
190     * the implementation.
191     * Whether supplementary characters should be considered is dependent
192     * on the needs of the caller. Since this method accepts the 'char' type
193     * then such chars are always represented by a pair. From a rendering
194     * perspective these will all (in the cases I know of) still be one
195     * unicode character -> one glyph. But if a caller is using this to
196     * discover any case where it cannot make naive assumptions about
197     * the number of chars, and how to index through them, then it may
198     * need the option to have a 'true' return in such a case.
199     */
200    public static boolean isComplexText(char [] chs, int start, int limit) {
201
202        for (int i = start; i < limit; i++) {
203            if (chs[i] < MIN_LAYOUT_CHARCODE) {
204                continue;
205            }
206            else if (isNonSimpleChar(chs[i])) {
207                return true;
208            }
209        }
210        return false;
211    }
212
213    /* This is almost the same as the method above, except it takes a
214     * char which means it may include undecoded surrogate pairs.
215     * The distinction is made so that code which needs to identify all
216     * cases in which we do not have a simple mapping from
217     * char->unicode character->glyph can be identified.
218     * For example measurement cannot simply sum advances of 'chars',
219     * the caret in editable text cannot advance one 'char' at a time, etc.
220     * These callers really are asking for more than whether 'layout'
221     * needs to be run, they need to know if they can assume 1->1
222     * char->glyph mapping.
223     */
224    public static boolean isNonSimpleChar(char ch) {
225        return
226            isComplexCharCode(ch) ||
227            (ch >= CharToGlyphMapper.HI_SURROGATE_START &&
228             ch <= CharToGlyphMapper.LO_SURROGATE_END);
229    }
230
231    /* If the character code falls into any of a number of unicode ranges
232     * where we know that simple left->right layout mapping chars to glyphs
233     * 1:1 and accumulating advances is going to produce incorrect results,
234     * we want to know this so the caller can use a more intelligent layout
235     * approach. A caller who cares about optimum performance may want to
236     * check the first case and skip the method call if its in that range.
237     * Although there's a lot of tests in here, knowing you can skip
238     * CTL saves a great deal more. The rest of the checks are ordered
239     * so that rather than checking explicitly if (>= start & <= end)
240     * which would mean all ranges would need to be checked so be sure
241     * CTL is not needed, the method returns as soon as it recognises
242     * the code point is outside of a CTL ranges.
243     * NOTE: Since this method accepts an 'int' it is asssumed to properly
244     * represent a CHARACTER. ie it assumes the caller has already
245     * converted surrogate pairs into supplementary characters, and so
246     * can handle this case and doesn't need to be told such a case is
247     * 'complex'.
248     */
249    public static boolean isComplexCharCode(int code) {
250
251        if (code < MIN_LAYOUT_CHARCODE || code > MAX_LAYOUT_CHARCODE) {
252            return false;
253        }
254        else if (code <= 0x036f) {
255            // Trigger layout for combining diacriticals 0x0300->0x036f
256            return true;
257        }
258        else if (code < 0x0590) {
259            // No automatic layout for Greek, Cyrillic, Armenian.
260             return false;
261        }
262        else if (code <= 0x06ff) {
263            // Hebrew 0590 - 05ff
264            // Arabic 0600 - 06ff
265            return true;
266        }
267        else if (code < 0x0900) {
268            return false; // Syriac and Thaana
269        }
270        else if (code <= 0x0e7f) {
271            // if Indic, assume shaping for conjuncts, reordering:
272            // 0900 - 097F Devanagari
273            // 0980 - 09FF Bengali
274            // 0A00 - 0A7F Gurmukhi
275            // 0A80 - 0AFF Gujarati
276            // 0B00 - 0B7F Oriya
277            // 0B80 - 0BFF Tamil
278            // 0C00 - 0C7F Telugu
279            // 0C80 - 0CFF Kannada
280            // 0D00 - 0D7F Malayalam
281            // 0D80 - 0DFF Sinhala
282            // 0E00 - 0E7F if Thai, assume shaping for vowel, tone marks
283            return true;
284        }
285        else if (code <  0x0f00) {
286            return false;
287        }
288        else if (code <= 0x0fff) { // U+0F00 - U+0FFF Tibetan
289            return true;
290        }
291        else if (code < 0x1100) {
292            return false;
293        }
294        else if (code < 0x11ff) { // U+1100 - U+11FF Old Hangul
295            return true;
296        }
297        else if (code < 0x1780) {
298            return false;
299        }
300        else if (code <= 0x17ff) { // 1780 - 17FF Khmer
301            return true;
302        }
303        else if (code < 0x200c) {
304            return false;
305        }
306        else if (code <= 0x200d) { //  zwj or zwnj
307            return true;
308        }
309        else if (code >= 0x202a && code <= 0x202e) { // directional control
310            return true;
311        }
312        else if (code >= 0x206a && code <= 0x206f) { // directional control
313            return true;
314        }
315        return false;
316    }
317
318    public static PlatformLogger getLogger() {
319        return logger;
320    }
321
322    public static boolean isLogging() {
323        return logging;
324    }
325
326    public static boolean debugFonts() {
327        return debugFonts;
328    }
329
330
331    // The following methods are used by Swing.
332
333    /* Revise the implementation to in fact mean "font is a composite font.
334     * This ensures that Swing components will always benefit from the
335     * fall back fonts
336     */
337    public static boolean fontSupportsDefaultEncoding(Font font) {
338        return getFont2D(font) instanceof CompositeFont;
339    }
340
341    /**
342     * This method is provided for internal and exclusive use by Swing.
343     *
344     * It may be used in conjunction with fontSupportsDefaultEncoding(Font)
345     * In the event that a desktop properties font doesn't directly
346     * support the default encoding, (ie because the host OS supports
347     * adding support for the current locale automatically for native apps),
348     * then Swing calls this method to get a font which  uses the specified
349     * font for the code points it covers, but also supports this locale
350     * just as the standard composite fonts do.
351     * Note: this will over-ride any setting where an application
352     * specifies it prefers locale specific composite fonts.
353     * The logic for this, is that this method is used only where the user or
354     * application has specified that the native L&F be used, and that
355     * we should honour that request to use the same font as native apps use.
356     *
357     * The behaviour of this method is to construct a new composite
358     * Font object that uses the specified physical font as its first
359     * component, and adds all the components of "dialog" as fall back
360     * components.
361     * The method currently assumes that only the size and style attributes
362     * are set on the specified font. It doesn't copy the font transform or
363     * other attributes because they aren't set on a font created from
364     * the desktop. This will need to be fixed if use is broadened.
365     *
366     * Operations such as Font.deriveFont will work properly on the
367     * font returned by this method for deriving a different point size.
368     * Additionally it tries to support a different style by calling
369     * getNewComposite() below. That also supports replacing slot zero
370     * with a different physical font but that is expected to be "rare".
371     * Deriving with a different style is needed because its been shown
372     * that some applications try to do this for Swing FontUIResources.
373     * Also operations such as new Font(font.getFontName(..), Font.PLAIN, 14);
374     * will NOT yield the same result, as the new underlying CompositeFont
375     * cannot be "looked up" in the font registry.
376     * This returns a FontUIResource as that is the Font sub-class needed
377     * by Swing.
378     * Suggested usage is something like :
379     * FontUIResource fuir;
380     * Font desktopFont = getDesktopFont(..);
381     * // NOTE even if fontSupportsDefaultEncoding returns true because
382     * // you get Tahoma and are running in an English locale, you may
383     * // still want to just call getCompositeFontUIResource() anyway
384     * // as only then will you get fallback fonts - eg for CJK.
385     * if (FontManager.fontSupportsDefaultEncoding(desktopFont)) {
386     *   fuir = new FontUIResource(..);
387     * } else {
388     *   fuir = FontManager.getCompositeFontUIResource(desktopFont);
389     * }
390     * return fuir;
391     */
392    private static volatile
393        SoftReference<ConcurrentHashMap<PhysicalFont, CompositeFont>>
394        compMapRef = new SoftReference<>(null);
395
396    public static FontUIResource getCompositeFontUIResource(Font font) {
397
398        FontUIResource fuir = new FontUIResource(font);
399        Font2D font2D = FontUtilities.getFont2D(font);
400
401        if (!(font2D instanceof PhysicalFont)) {
402            /* Swing should only be calling this when a font is obtained
403             * from desktop properties, so should generally be a physical font,
404             * an exception might be for names like "MS Serif" which are
405             * automatically mapped to "Serif", so there's no need to do
406             * anything special in that case. But note that suggested usage
407             * is first to call fontSupportsDefaultEncoding(Font) and this
408             * method should not be called if that were to return true.
409             */
410             return fuir;
411        }
412
413        FontManager fm = FontManagerFactory.getInstance();
414        Font2D dialog = fm.findFont2D("dialog", font.getStyle(), FontManager.NO_FALLBACK);
415        // Should never be null, but MACOSX fonts are not CompositeFonts
416        if (dialog == null || !(dialog instanceof CompositeFont)) {
417            return fuir;
418        }
419        CompositeFont dialog2D = (CompositeFont)dialog;
420        PhysicalFont physicalFont = (PhysicalFont)font2D;
421        ConcurrentHashMap<PhysicalFont, CompositeFont> compMap = compMapRef.get();
422        if (compMap == null) { // Its been collected.
423            compMap = new ConcurrentHashMap<PhysicalFont, CompositeFont>();
424            compMapRef = new SoftReference<>(compMap);
425        }
426        CompositeFont compFont = compMap.get(physicalFont);
427        if (compFont == null) {
428            compFont = new CompositeFont(physicalFont, dialog2D);
429            compMap.put(physicalFont, compFont);
430        }
431        FontAccess.getFontAccess().setFont2D(fuir, compFont.handle);
432        /* marking this as a created font is needed as only created fonts
433         * copy their creator's handles.
434         */
435        FontAccess.getFontAccess().setCreatedFont(fuir);
436        return fuir;
437    }
438
439   /* A small "map" from GTK/fontconfig names to the equivalent JDK
440    * logical font name.
441    */
442    private static final String[][] nameMap = {
443        {"sans",       "sansserif"},
444        {"sans-serif", "sansserif"},
445        {"serif",      "serif"},
446        {"monospace",  "monospaced"}
447    };
448
449    public static String mapFcName(String name) {
450        for (int i = 0; i < nameMap.length; i++) {
451            if (name.equals(nameMap[i][0])) {
452                return nameMap[i][1];
453            }
454        }
455        return null;
456    }
457
458
459    /* This is called by Swing passing in a fontconfig family name
460     * such as "sans". In return Swing gets a FontUIResource instance
461     * that has queried fontconfig to resolve the font(s) used for this.
462     * Fontconfig will if asked return a list of fonts to give the largest
463     * possible code point coverage.
464     * For now we use only the first font returned by fontconfig, and
465     * back it up with the most closely matching JDK logical font.
466     * Essentially this means pre-pending what we return now with fontconfig's
467     * preferred physical font. This could lead to some duplication in cases,
468     * if we already included that font later. We probably should remove such
469     * duplicates, but it is not a significant problem. It can be addressed
470     * later as part of creating a Composite which uses more of the
471     * same fonts as fontconfig. At that time we also should pay more
472     * attention to the special rendering instructions fontconfig returns,
473     * such as whether we should prefer embedded bitmaps over antialiasing.
474     * There's no way to express that via a Font at present.
475     */
476    public static FontUIResource getFontConfigFUIR(String fcFamily,
477                                                   int style, int size) {
478
479        String mapped = mapFcName(fcFamily);
480        if (mapped == null) {
481            mapped = "sansserif";
482        }
483
484        FontUIResource fuir;
485        FontManager fm = FontManagerFactory.getInstance();
486        if (fm instanceof SunFontManager) {
487            SunFontManager sfm = (SunFontManager) fm;
488            fuir = sfm.getFontConfigFUIR(mapped, style, size);
489        } else {
490            fuir = new FontUIResource(mapped, style, size);
491        }
492        return fuir;
493    }
494
495
496    /**
497     * Used by windows printing to assess if a font is likely to
498     * be layout compatible with JDK
499     * TrueType fonts should be, but if they have no GPOS table,
500     * but do have a GSUB table, then they are probably older
501     * fonts GDI handles differently.
502     */
503    public static boolean textLayoutIsCompatible(Font font) {
504
505        Font2D font2D = getFont2D(font);
506        if (font2D instanceof TrueTypeFont) {
507            TrueTypeFont ttf = (TrueTypeFont) font2D;
508            return
509                ttf.getDirectoryEntry(TrueTypeFont.GSUBTag) == null ||
510                ttf.getDirectoryEntry(TrueTypeFont.GPOSTag) != null;
511        } else {
512            return false;
513        }
514    }
515
516}
517