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