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     public static boolean isMacOSX14;
  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 
  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                 isSolaris = osName.startsWith("SunOS");
  71 
  72                 isLinux = osName.startsWith("Linux");
  73 
  74                 isMacOSX = osName.contains("OS X"); // TODO: MacOSX
  75                 if (isMacOSX) {
  76                     // os.version has values like 10.13.6, 10.14.6
  77                     // If it is not positively recognised as 10.13 or less,
  78                     // assume it means 10.14 or some later version.
  79                     isMacOSX14 = true;
  80                     String version = System.getProperty("os.version", "");
  81                     if (version.startsWith("10.")) {
  82                         version = version.substring(3);
  83                         int periodIndex = version.indexOf('.');
  84                         if (periodIndex != -1) {
  85                             version = version.substring(0, periodIndex);
  86                         }
  87                         try {
  88                             int v = Integer.parseInt(version);
  89                             isMacOSX14 = (v >= 14);
  90                         } catch (NumberFormatException e) {
  91                         }
  92                      }
  93                  }
  94                 /* If set to "jdk", use the JDK's scaler rather than
  95                  * the platform one. This may be a no-op on platforms where
  96                  * JDK has been configured so that it always relies on the
  97                  * platform scaler. The principal case where it has an
  98                  * effect is that on Windows, 2D will never use GDI.
  99                  */
 100                 String scalerStr = System.getProperty("sun.java2d.font.scaler");
 101                 if (scalerStr != null) {
 102                     useJDKScaler = "jdk".equals(scalerStr);
 103                 } else {
 104                     useJDKScaler = false;
 105                 }
 106                 isWindows = osName.startsWith("Windows");
 107                 String debugLevel =
 108                     System.getProperty("sun.java2d.debugfonts");
 109 
 110                 if (debugLevel != null && !debugLevel.equals("false")) {
 111                     debugFonts = true;
 112                     logger = PlatformLogger.getLogger("sun.java2d");
 113                     if (debugLevel.equals("warning")) {
 114                         logger.setLevel(PlatformLogger.Level.WARNING);
 115                     } else if (debugLevel.equals("severe")) {
 116                         logger.setLevel(PlatformLogger.Level.SEVERE);
 117                     }
 118                 }
 119 
 120                 if (debugFonts) {
 121                     logger = PlatformLogger.getLogger("sun.java2d");
 122                     logging = logger.isEnabled();
 123                 }
 124 
 125                 return null;
 126             }
 127         });
 128     }
 129 
 130     /**
 131      * Referenced by code in the JDK which wants to test for the
 132      * minimum char code for which layout may be required.
 133      * Note that even basic latin text can benefit from ligatures,
 134      * eg "ffi" but we presently apply those only if explicitly
 135      * requested with TextAttribute.LIGATURES_ON.
 136      * The value here indicates the lowest char code for which failing
 137      * to invoke layout would prevent acceptable rendering.
 138      */
 139     public static final int MIN_LAYOUT_CHARCODE = 0x0300;
 140 
 141     /**
 142      * Referenced by code in the JDK which wants to test for the
 143      * maximum char code for which layout may be required.
 144      * Note this does not account for supplementary characters
 145      * where the caller interprets 'layout' to mean any case where
 146      * one 'char' (ie the java type char) does not map to one glyph
 147      */
 148     public static final int MAX_LAYOUT_CHARCODE = 0x206F;
 149 
 150     /**
 151      * Calls the private getFont2D() method in java.awt.Font objects.
 152      *
 153      * @param font the font object to call
 154      *
 155      * @return the Font2D object returned by Font.getFont2D()
 156      */
 157     public static Font2D getFont2D(Font font) {
 158         return FontAccess.getFontAccess().getFont2D(font);
 159     }
 160 
 161     /**
 162      * Return true if there any characters which would trigger layout.
 163      * This method considers supplementary characters to be simple,
 164      * since we do not presently invoke layout on any code points in
 165      * outside the BMP.
 166      */
 167     public static boolean isComplexScript(char [] chs, int start, int limit) {
 168 
 169         for (int i = start; i < limit; i++) {
 170             if (chs[i] < MIN_LAYOUT_CHARCODE) {
 171                 continue;
 172             }
 173             else if (isComplexCharCode(chs[i])) {
 174                 return true;
 175             }
 176         }
 177         return false;
 178     }
 179 
 180     /**
 181      * If there is anything in the text which triggers a case
 182      * where char->glyph does not map 1:1 in straightforward
 183      * left->right ordering, then this method returns true.
 184      * Scripts which might require it but are not treated as such
 185      * due to JDK implementations will not return true.
 186      * ie a 'true' return is an indication of the treatment by
 187      * the implementation.
 188      * Whether supplementary characters should be considered is dependent
 189      * on the needs of the caller. Since this method accepts the 'char' type
 190      * then such chars are always represented by a pair. From a rendering
 191      * perspective these will all (in the cases I know of) still be one
 192      * unicode character -> one glyph. But if a caller is using this to
 193      * discover any case where it cannot make naive assumptions about
 194      * the number of chars, and how to index through them, then it may
 195      * need the option to have a 'true' return in such a case.
 196      */
 197     public static boolean isComplexText(char [] chs, int start, int limit) {
 198 
 199         for (int i = start; i < limit; i++) {
 200             if (chs[i] < MIN_LAYOUT_CHARCODE) {
 201                 continue;
 202             }
 203             else if (isNonSimpleChar(chs[i])) {
 204                 return true;
 205             }
 206         }
 207         return false;
 208     }
 209 
 210     /* This is almost the same as the method above, except it takes a
 211      * char which means it may include undecoded surrogate pairs.
 212      * The distinction is made so that code which needs to identify all
 213      * cases in which we do not have a simple mapping from
 214      * char->unicode character->glyph can be identified.
 215      * For example measurement cannot simply sum advances of 'chars',
 216      * the caret in editable text cannot advance one 'char' at a time, etc.
 217      * These callers really are asking for more than whether 'layout'
 218      * needs to be run, they need to know if they can assume 1->1
 219      * char->glyph mapping.
 220      */
 221     public static boolean isNonSimpleChar(char ch) {
 222         return
 223             isComplexCharCode(ch) ||
 224             (ch >= CharToGlyphMapper.HI_SURROGATE_START &&
 225              ch <= CharToGlyphMapper.LO_SURROGATE_END);
 226     }
 227 
 228     /* If the character code falls into any of a number of unicode ranges
 229      * where we know that simple left->right layout mapping chars to glyphs
 230      * 1:1 and accumulating advances is going to produce incorrect results,
 231      * we want to know this so the caller can use a more intelligent layout
 232      * approach. A caller who cares about optimum performance may want to
 233      * check the first case and skip the method call if its in that range.
 234      * Although there's a lot of tests in here, knowing you can skip
 235      * CTL saves a great deal more. The rest of the checks are ordered
 236      * so that rather than checking explicitly if (>= start & <= end)
 237      * which would mean all ranges would need to be checked so be sure
 238      * CTL is not needed, the method returns as soon as it recognises
 239      * the code point is outside of a CTL ranges.
 240      * NOTE: Since this method accepts an 'int' it is asssumed to properly
 241      * represent a CHARACTER. ie it assumes the caller has already
 242      * converted surrogate pairs into supplementary characters, and so
 243      * can handle this case and doesn't need to be told such a case is
 244      * 'complex'.
 245      */
 246     public static boolean isComplexCharCode(int code) {
 247 
 248         if (code < MIN_LAYOUT_CHARCODE || code > MAX_LAYOUT_CHARCODE) {
 249             return false;
 250         }
 251         else if (code <= 0x036f) {
 252             // Trigger layout for combining diacriticals 0x0300->0x036f
 253             return true;
 254         }
 255         else if (code < 0x0590) {
 256             // No automatic layout for Greek, Cyrillic, Armenian.
 257              return false;
 258         }
 259         else if (code <= 0x06ff) {
 260             // Hebrew 0590 - 05ff
 261             // Arabic 0600 - 06ff
 262             return true;
 263         }
 264         else if (code < 0x0900) {
 265             return false; // Syriac and Thaana
 266         }
 267         else if (code <= 0x0e7f) {
 268             // if Indic, assume shaping for conjuncts, reordering:
 269             // 0900 - 097F Devanagari
 270             // 0980 - 09FF Bengali
 271             // 0A00 - 0A7F Gurmukhi
 272             // 0A80 - 0AFF Gujarati
 273             // 0B00 - 0B7F Oriya
 274             // 0B80 - 0BFF Tamil
 275             // 0C00 - 0C7F Telugu
 276             // 0C80 - 0CFF Kannada
 277             // 0D00 - 0D7F Malayalam
 278             // 0D80 - 0DFF Sinhala
 279             // 0E00 - 0E7F if Thai, assume shaping for vowel, tone marks
 280             return true;
 281         }
 282         else if (code <  0x0f00) {
 283             return false;
 284         }
 285         else if (code <= 0x0fff) { // U+0F00 - U+0FFF Tibetan
 286             return true;
 287         }
 288         else if (code < 0x10A0) {  // U+1000 - U+109F Myanmar
 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      * if (FontManager.fontSupportsDefaultEncoding(desktopFont)) {
 382      *   fuir = new FontUIResource(desktopFont);
 383      * } else {
 384      *   fuir = FontManager.getCompositeFontUIResource(desktopFont);
 385      * }
 386      * return fuir;
 387      */
 388     private static volatile
 389         SoftReference<ConcurrentHashMap<PhysicalFont, CompositeFont>>
 390         compMapRef = new SoftReference<>(null);
 391 
 392     public static FontUIResource getCompositeFontUIResource(Font font) {
 393 
 394         FontUIResource fuir = new FontUIResource(font);
 395         Font2D font2D = FontUtilities.getFont2D(font);
 396 
 397         if (!(font2D instanceof PhysicalFont)) {
 398             /* Swing should only be calling this when a font is obtained
 399              * from desktop properties, so should generally be a physical font,
 400              * an exception might be for names like "MS Serif" which are
 401              * automatically mapped to "Serif", so there's no need to do
 402              * anything special in that case. But note that suggested usage
 403              * is first to call fontSupportsDefaultEncoding(Font) and this
 404              * method should not be called if that were to return true.
 405              */
 406              return fuir;
 407         }
 408 
 409         FontManager fm = FontManagerFactory.getInstance();
 410         Font2D dialog = fm.findFont2D("dialog", font.getStyle(), FontManager.NO_FALLBACK);
 411         // Should never be null, but MACOSX fonts are not CompositeFonts
 412         if (dialog == null || !(dialog instanceof CompositeFont)) {
 413             return fuir;
 414         }
 415         CompositeFont dialog2D = (CompositeFont)dialog;
 416         PhysicalFont physicalFont = (PhysicalFont)font2D;
 417         ConcurrentHashMap<PhysicalFont, CompositeFont> compMap = compMapRef.get();
 418         if (compMap == null) { // Its been collected.
 419             compMap = new ConcurrentHashMap<PhysicalFont, CompositeFont>();
 420             compMapRef = new SoftReference<>(compMap);
 421         }
 422         CompositeFont compFont = compMap.get(physicalFont);
 423         if (compFont == null) {
 424             compFont = new CompositeFont(physicalFont, dialog2D);
 425             compMap.put(physicalFont, compFont);
 426         }
 427         FontAccess.getFontAccess().setFont2D(fuir, compFont.handle);
 428         /* marking this as a created font is needed as only created fonts
 429          * copy their creator's handles.
 430          */
 431         FontAccess.getFontAccess().setCreatedFont(fuir);
 432         return fuir;
 433     }
 434 
 435    /* A small "map" from GTK/fontconfig names to the equivalent JDK
 436     * logical font name.
 437     */
 438     private static final String[][] nameMap = {
 439         {"sans",       "sansserif"},
 440         {"sans-serif", "sansserif"},
 441         {"serif",      "serif"},
 442         {"monospace",  "monospaced"}
 443     };
 444 
 445     public static String mapFcName(String name) {
 446         for (int i = 0; i < nameMap.length; i++) {
 447             if (name.equals(nameMap[i][0])) {
 448                 return nameMap[i][1];
 449             }
 450         }
 451         return null;
 452     }
 453 
 454 
 455     /* This is called by Swing passing in a fontconfig family name
 456      * such as "sans". In return Swing gets a FontUIResource instance
 457      * that has queried fontconfig to resolve the font(s) used for this.
 458      * Fontconfig will if asked return a list of fonts to give the largest
 459      * possible code point coverage.
 460      * For now we use only the first font returned by fontconfig, and
 461      * back it up with the most closely matching JDK logical font.
 462      * Essentially this means pre-pending what we return now with fontconfig's
 463      * preferred physical font. This could lead to some duplication in cases,
 464      * if we already included that font later. We probably should remove such
 465      * duplicates, but it is not a significant problem. It can be addressed
 466      * later as part of creating a Composite which uses more of the
 467      * same fonts as fontconfig. At that time we also should pay more
 468      * attention to the special rendering instructions fontconfig returns,
 469      * such as whether we should prefer embedded bitmaps over antialiasing.
 470      * There's no way to express that via a Font at present.
 471      */
 472     public static FontUIResource getFontConfigFUIR(String fcFamily,
 473                                                    int style, int size) {
 474 
 475         String mapped = mapFcName(fcFamily);
 476         if (mapped == null) {
 477             mapped = "sansserif";
 478         }
 479 
 480         FontUIResource fuir;
 481         FontManager fm = FontManagerFactory.getInstance();
 482         if (fm instanceof SunFontManager) {
 483             SunFontManager sfm = (SunFontManager) fm;
 484             fuir = sfm.getFontConfigFUIR(mapped, style, size);
 485         } else {
 486             fuir = new FontUIResource(mapped, style, size);
 487         }
 488         return fuir;
 489     }
 490 
 491 
 492     /**
 493      * Used by windows printing to assess if a font is likely to
 494      * be layout compatible with JDK
 495      * TrueType fonts should be, but if they have no GPOS table,
 496      * but do have a GSUB table, then they are probably older
 497      * fonts GDI handles differently.
 498      */
 499     public static boolean textLayoutIsCompatible(Font font) {
 500 
 501         Font2D font2D = getFont2D(font);
 502         if (font2D instanceof TrueTypeFont) {
 503             TrueTypeFont ttf = (TrueTypeFont) font2D;
 504             return
 505                 ttf.getDirectoryEntry(TrueTypeFont.GSUBTag) == null ||
 506                 ttf.getDirectoryEntry(TrueTypeFont.GPOSTag) != null;
 507         } else {
 508             return false;
 509         }
 510     }
 511 
 512 }