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