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