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