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 java.security.PrivilegedAction;
  36 import javax.swing.plaf.FontUIResource;
  37 
  38 import sun.util.logging.PlatformLogger;
  39 
  40 /**
  41  * A collection of utility methods.
  42  */
  43 public final class FontUtilities {
  44 
  45     public static boolean isSolaris;
  46 
  47     public static boolean isLinux;
  48 
  49     public static boolean isSolaris8;
  50 
  51     public static boolean isSolaris9;
  52 
  53     public static boolean isOpenSolaris;
  54 
  55     public static boolean useT2K;
  56 
  57     public static boolean isWindows;
  58 
  59     public static 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         AccessController.doPrivileged(new PrivilegedAction () {
  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                 String t2kStr = System.getProperty("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 = System.getProperty("os.version", "0.0");
  81                     isSolaris8 = version.startsWith("5.8");
  82                     isSolaris9 = version.startsWith("5.9");
  83                     float ver = Float.parseFloat(version);
  84                     if (ver > 5.10f) {
  85                         File f = new File("/etc/release");
  86                         String line = null;
  87                         try {
  88                             FileInputStream fis = new FileInputStream(f);
  89                             InputStreamReader isr = new InputStreamReader(
  90                                                             fis, "ISO-8859-1");
  91                             BufferedReader br = new BufferedReader(isr);
  92                             line = br.readLine();
  93                             fis.close();
  94                         } catch (Exception ex) {
  95                             // Nothing to do here.
  96                         }
  97                         if (line != null && line.indexOf("OpenSolaris") >= 0) {
  98                             isOpenSolaris = true;
  99                         } else {
 100                             isOpenSolaris = false;
 101                         }
 102                     } else {
 103                         isOpenSolaris = false;
 104                     }
 105                 } else {
 106                     isSolaris8 = false;
 107                     isSolaris9 = false;
 108                     isOpenSolaris = false;
 109                 }
 110                 isWindows = osName.startsWith("Windows");
 111                 String jreLibDirName = System.getProperty("java.home", "")
 112                                                       + File.separator + "lib";
 113                 String jreFontDirName =
 114                         jreLibDirName + File.separator + "fonts";
 115                 File lucidaFile = new File(jreFontDirName + File.separator
 116                                            + LUCIDA_FILE_NAME);
 117                 isOpenJDK = !lucidaFile.exists();
 118                 return null;
 119             }
 120         });
 121     }
 122 
 123     /**
 124      * Referenced by code in the JDK which wants to test for the
 125      * minimum char code for which layout may be required.
 126      * Note that even basic latin text can benefit from ligatures,
 127      * eg "ffi" but we presently apply those only if explicitly
 128      * requested with TextAttribute.LIGATURES_ON.
 129      * The value here indicates the lowest char code for which failing
 130      * to invoke layout would prevent acceptable rendering.
 131      */
 132     public static final int MIN_LAYOUT_CHARCODE = 0x0300;
 133 
 134     /**
 135      * Referenced by code in the JDK which wants to test for the
 136      * maximum char code for which layout may be required.
 137      * Note this does not account for supplementary characters
 138      * where the caller interprets 'layout' to mean any case where
 139      * one 'char' (ie the java type char) does not map to one glyph
 140      */
 141     public static final int MAX_LAYOUT_CHARCODE = 0x206F;
 142 
 143     private static boolean debugFonts = false;
 144     private static PlatformLogger logger = null;
 145     private static boolean logging;
 146 
 147     static {
 148 
 149         String debugLevel =
 150             System.getProperty("sun.java2d.debugfonts");
 151 
 152         if (debugLevel != null && !debugLevel.equals("false")) {
 153             debugFonts = true;
 154             logger = PlatformLogger.getLogger("sun.java2d");
 155             if (debugLevel.equals("warning")) {
 156                 logger.setLevel(PlatformLogger.WARNING);
 157             } else if (debugLevel.equals("severe")) {
 158                 logger.setLevel(PlatformLogger.SEVERE);
 159             }
 160         }
 161 
 162         if (debugFonts) {
 163             logger = PlatformLogger.getLogger("sun.java2d");
 164             logging = logger.isEnabled();
 165         }
 166 
 167     }
 168 
 169     /**
 170      * Calls the private getFont2D() method in java.awt.Font objects.
 171      *
 172      * @param font the font object to call
 173      *
 174      * @return the Font2D object returned by Font.getFont2D()
 175      */
 176     public static Font2D getFont2D(Font font) {
 177         return FontAccess.getFontAccess().getFont2D(font);
 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 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 < 0x1780) {
 283             return false;
 284         }
 285         else if (code <= 0x17ff) { // 1780 - 17FF Khmer
 286             return true;
 287         }
 288         else if (code < 0x200c) {
 289             return false;
 290         }
 291         else if (code <= 0x200d) { //  zwj or zwnj
 292             return true;
 293         }
 294         else if (code >= 0x202a && code <= 0x202e) { // directional control
 295             return true;
 296         }
 297         else if (code >= 0x206a && code <= 0x206f) { // directional control
 298             return true;
 299         }
 300         return false;
 301     }
 302 
 303     public static PlatformLogger getLogger() {
 304         return logger;
 305     }
 306 
 307     public static boolean isLogging() {
 308         return logging;
 309     }
 310 
 311     public static boolean debugFonts() {
 312         return debugFonts;
 313     }
 314 
 315 
 316     // The following methods are used by Swing.
 317 
 318     /* Revise the implementation to in fact mean "font is a composite font.
 319      * This ensures that Swing components will always benefit from the
 320      * fall back fonts
 321      */
 322     public static boolean fontSupportsDefaultEncoding(Font font) {
 323         return getFont2D(font) instanceof CompositeFont;
 324     }
 325 
 326     /**
 327      * This method is provided for internal and exclusive use by Swing.
 328      *
 329      * It may be used in conjunction with fontSupportsDefaultEncoding(Font)
 330      * In the event that a desktop properties font doesn't directly
 331      * support the default encoding, (ie because the host OS supports
 332      * adding support for the current locale automatically for native apps),
 333      * then Swing calls this method to get a font which  uses the specified
 334      * font for the code points it covers, but also supports this locale
 335      * just as the standard composite fonts do.
 336      * Note: this will over-ride any setting where an application
 337      * specifies it prefers locale specific composite fonts.
 338      * The logic for this, is that this method is used only where the user or
 339      * application has specified that the native L&F be used, and that
 340      * we should honour that request to use the same font as native apps use.
 341      *
 342      * The behaviour of this method is to construct a new composite
 343      * Font object that uses the specified physical font as its first
 344      * component, and adds all the components of "dialog" as fall back
 345      * components.
 346      * The method currently assumes that only the size and style attributes
 347      * are set on the specified font. It doesn't copy the font transform or
 348      * other attributes because they aren't set on a font created from
 349      * the desktop. This will need to be fixed if use is broadened.
 350      *
 351      * Operations such as Font.deriveFont will work properly on the
 352      * font returned by this method for deriving a different point size.
 353      * Additionally it tries to support a different style by calling
 354      * getNewComposite() below. That also supports replacing slot zero
 355      * with a different physical font but that is expected to be "rare".
 356      * Deriving with a different style is needed because its been shown
 357      * that some applications try to do this for Swing FontUIResources.
 358      * Also operations such as new Font(font.getFontName(..), Font.PLAIN, 14);
 359      * will NOT yield the same result, as the new underlying CompositeFont
 360      * cannot be "looked up" in the font registry.
 361      * This returns a FontUIResource as that is the Font sub-class needed
 362      * by Swing.
 363      * Suggested usage is something like :
 364      * FontUIResource fuir;
 365      * Font desktopFont = getDesktopFont(..);
 366      * // NOTE even if fontSupportsDefaultEncoding returns true because
 367      * // you get Tahoma and are running in an English locale, you may
 368      * // still want to just call getCompositeFontUIResource() anyway
 369      * // as only then will you get fallback fonts - eg for CJK.
 370      * if (FontManager.fontSupportsDefaultEncoding(desktopFont)) {
 371      *   fuir = new FontUIResource(..);
 372      * } else {
 373      *   fuir = FontManager.getCompositeFontUIResource(desktopFont);
 374      * }
 375      * return fuir;
 376      */
 377     public static FontUIResource getCompositeFontUIResource(Font font) {
 378 
 379         FontUIResource fuir =
 380             new FontUIResource(font.getName(),font.getStyle(),font.getSize());
 381         Font2D font2D = FontUtilities.getFont2D(font);
 382 
 383         if (!(font2D instanceof PhysicalFont)) {
 384             /* Swing should only be calling this when a font is obtained
 385              * from desktop properties, so should generally be a physical font,
 386              * an exception might be for names like "MS Serif" which are
 387              * automatically mapped to "Serif", so there's no need to do
 388              * anything special in that case. But note that suggested usage
 389              * is first to call fontSupportsDefaultEncoding(Font) and this
 390              * method should not be called if that were to return true.
 391              */
 392              return fuir;
 393         }
 394 
 395         FontManager fm = FontManagerFactory.getInstance();
 396         CompositeFont dialog2D =
 397           (CompositeFont) fm.findFont2D("dialog", font.getStyle(), FontManager.NO_FALLBACK);
 398         if (dialog2D == null) { /* shouldn't happen */
 399             return fuir;
 400         }
 401         PhysicalFont physicalFont = (PhysicalFont)font2D;
 402         CompositeFont compFont = new CompositeFont(physicalFont, dialog2D);
 403         FontAccess.getFontAccess().setFont2D(fuir, compFont.handle);
 404         /* marking this as a created font is needed as only created fonts
 405          * copy their creator's handles.
 406          */
 407         FontAccess.getFontAccess().setCreatedFont(fuir);
 408         return fuir;
 409     }
 410 
 411    /* A small "map" from GTK/fontconfig names to the equivalent JDK
 412     * logical font name.
 413     */
 414     private static final String[][] nameMap = {
 415         {"sans",       "sansserif"},
 416         {"sans-serif", "sansserif"},
 417         {"serif",      "serif"},
 418         {"monospace",  "monospaced"}
 419     };
 420 
 421     public static String mapFcName(String name) {
 422         for (int i = 0; i < nameMap.length; i++) {
 423             if (name.equals(nameMap[i][0])) {
 424                 return nameMap[i][1];
 425             }
 426         }
 427         return null;
 428     }
 429 
 430 
 431     /* This is called by Swing passing in a fontconfig family name
 432      * such as "sans". In return Swing gets a FontUIResource instance
 433      * that has queried fontconfig to resolve the font(s) used for this.
 434      * Fontconfig will if asked return a list of fonts to give the largest
 435      * possible code point coverage.
 436      * For now we use only the first font returned by fontconfig, and
 437      * back it up with the most closely matching JDK logical font.
 438      * Essentially this means pre-pending what we return now with fontconfig's
 439      * preferred physical font. This could lead to some duplication in cases,
 440      * if we already included that font later. We probably should remove such
 441      * duplicates, but it is not a significant problem. It can be addressed
 442      * later as part of creating a Composite which uses more of the
 443      * same fonts as fontconfig. At that time we also should pay more
 444      * attention to the special rendering instructions fontconfig returns,
 445      * such as whether we should prefer embedded bitmaps over antialiasing.
 446      * There's no way to express that via a Font at present.
 447      */
 448     public static FontUIResource getFontConfigFUIR(String fcFamily,
 449                                                    int style, int size) {
 450 
 451         String mapped = mapFcName(fcFamily);
 452         if (mapped == null) {
 453             mapped = "sansserif";
 454         }
 455 
 456         FontUIResource fuir;
 457         FontManager fm = FontManagerFactory.getInstance();
 458         if (fm instanceof SunFontManager) {
 459             SunFontManager sfm = (SunFontManager) fm;
 460             fuir = sfm.getFontConfigFUIR(mapped, style, size);
 461         } else {
 462             fuir = new FontUIResource(mapped, style, size);
 463         }
 464         return fuir;
 465     }
 466 
 467 
 468     /**
 469      * Used by windows printing to assess if a font is likely to
 470      * be layout compatible with JDK
 471      * TrueType fonts should be, but if they have no GPOS table,
 472      * but do have a GSUB table, then they are probably older
 473      * fonts GDI handles differently.
 474      */
 475     public static boolean textLayoutIsCompatible(Font font) {
 476 
 477         Font2D font2D = getFont2D(font);
 478         if (font2D instanceof TrueTypeFont) {
 479             TrueTypeFont ttf = (TrueTypeFont) font2D;
 480             return
 481                 ttf.getDirectoryEntry(TrueTypeFont.GSUBTag) == null ||
 482                 ttf.getDirectoryEntry(TrueTypeFont.GPOSTag) != null;
 483         } else {
 484             return false;
 485         }
 486     }
 487 
 488 }