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