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