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