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.awt.FontFormatException; 30 import java.io.BufferedReader; 31 import java.io.File; 32 import java.io.FileInputStream; 33 import java.io.FilenameFilter; 34 import java.io.IOException; 35 import java.io.InputStreamReader; 36 import java.security.AccessController; 37 import java.security.PrivilegedAction; 38 import java.util.ArrayList; 39 import java.util.HashMap; 40 import java.util.HashSet; 41 import java.util.Hashtable; 42 import java.util.Iterator; 43 import java.util.List; 44 import java.util.Locale; 45 import java.util.Map; 46 import java.util.NoSuchElementException; 47 import java.util.StringTokenizer; 48 import java.util.TreeMap; 49 import java.util.Vector; 50 import java.util.concurrent.ConcurrentHashMap; 51 52 import javax.swing.plaf.FontUIResource; 53 54 import sun.awt.FontConfiguration; 55 import sun.awt.SunToolkit; 56 import sun.awt.util.ThreadGroupUtils; 57 import sun.java2d.FontSupport; 58 import sun.util.logging.PlatformLogger; 59 60 /** 61 * The base implementation of the {@link FontManager} interface. It implements 62 * the platform independent, shared parts of OpenJDK's FontManager 63 * implementations. The platform specific parts are declared as abstract 64 * methods that have to be implemented by specific implementations. 65 */ 66 public abstract class SunFontManager implements FontSupport, FontManagerForSGE { 67 68 private static class TTFilter implements FilenameFilter { 69 public boolean accept(File dir,String name) { 70 /* all conveniently have the same suffix length */ 71 int offset = name.length()-4; 72 if (offset <= 0) { /* must be at least A.ttf */ 73 return false; 74 } else { 75 return(name.startsWith(".ttf", offset) || 76 name.startsWith(".TTF", offset) || 77 name.startsWith(".ttc", offset) || 78 name.startsWith(".TTC", offset) || 79 name.startsWith(".otf", offset) || 80 name.startsWith(".OTF", offset)); 81 } 82 } 83 } 84 85 private static class T1Filter implements FilenameFilter { 86 public boolean accept(File dir,String name) { 87 if (noType1Font) { 88 return false; 89 } 90 /* all conveniently have the same suffix length */ 91 int offset = name.length()-4; 92 if (offset <= 0) { /* must be at least A.pfa */ 93 return false; 94 } else { 95 return(name.startsWith(".pfa", offset) || 96 name.startsWith(".pfb", offset) || 97 name.startsWith(".PFA", offset) || 98 name.startsWith(".PFB", offset)); 99 } 100 } 101 } 102 103 private static class TTorT1Filter implements FilenameFilter { 104 public boolean accept(File dir, String name) { 105 106 /* all conveniently have the same suffix length */ 107 int offset = name.length()-4; 108 if (offset <= 0) { /* must be at least A.ttf or A.pfa */ 109 return false; 110 } else { 111 boolean isTT = 112 name.startsWith(".ttf", offset) || 113 name.startsWith(".TTF", offset) || 114 name.startsWith(".ttc", offset) || 115 name.startsWith(".TTC", offset) || 116 name.startsWith(".otf", offset) || 117 name.startsWith(".OTF", offset); 118 if (isTT) { 119 return true; 120 } else if (noType1Font) { 121 return false; 122 } else { 123 return(name.startsWith(".pfa", offset) || 124 name.startsWith(".pfb", offset) || 125 name.startsWith(".PFA", offset) || 126 name.startsWith(".PFB", offset)); 127 } 128 } 129 } 130 } 131 132 public static final int FONTFORMAT_NONE = -1; 133 public static final int FONTFORMAT_TRUETYPE = 0; 134 public static final int FONTFORMAT_TYPE1 = 1; 135 public static final int FONTFORMAT_TTC = 2; 136 public static final int FONTFORMAT_COMPOSITE = 3; 137 public static final int FONTFORMAT_NATIVE = 4; 138 139 /* Pool of 20 font file channels chosen because some UTF-8 locale 140 * composite fonts can use up to 16 platform fonts (including the 141 * Lucida fall back). This should prevent channel thrashing when 142 * dealing with one of these fonts. 143 * The pool array stores the fonts, rather than directly referencing 144 * the channels, as the font needs to do the open/close work. 145 */ 146 // MACOSX begin -- need to access these in subclass 147 protected static final int CHANNELPOOLSIZE = 20; 148 protected FileFont[] fontFileCache = new FileFont[CHANNELPOOLSIZE]; 149 // MACOSX end 150 private int lastPoolIndex = 0; 151 152 /* Need to implement a simple linked list scheme for fast 153 * traversal and lookup. 154 * Also want to "fast path" dialog so there's minimal overhead. 155 */ 156 /* There are at exactly 20 composite fonts: 5 faces (but some are not 157 * usually different), in 4 styles. The array may be auto-expanded 158 * later if more are needed, eg for user-defined composites or locale 159 * variants. 160 */ 161 private int maxCompFont = 0; 162 private CompositeFont [] compFonts = new CompositeFont[20]; 163 private ConcurrentHashMap<String, CompositeFont> 164 compositeFonts = new ConcurrentHashMap<String, CompositeFont>(); 165 private ConcurrentHashMap<String, PhysicalFont> 166 physicalFonts = new ConcurrentHashMap<String, PhysicalFont>(); 167 private ConcurrentHashMap<String, PhysicalFont> 168 registeredFonts = new ConcurrentHashMap<String, PhysicalFont>(); 169 170 /* given a full name find the Font. Remind: there's duplication 171 * here in that this contains the content of compositeFonts + 172 * physicalFonts. 173 */ 174 // MACOSX begin -- need to access this in subclass 175 protected ConcurrentHashMap<String, Font2D> 176 fullNameToFont = new ConcurrentHashMap<String, Font2D>(); 177 // MACOSX end 178 179 /* TrueType fonts have localised names. Support searching all 180 * of these before giving up on a name. 181 */ 182 private HashMap<String, TrueTypeFont> localeFullNamesToFont; 183 184 private PhysicalFont defaultPhysicalFont; 185 186 static boolean longAddresses; 187 private boolean loaded1dot0Fonts = false; 188 boolean loadedAllFonts = false; 189 boolean loadedAllFontFiles = false; 190 String[] jreOtherFontFiles; 191 boolean noOtherJREFontFiles = false; // initial assumption. 192 193 public static String jreLibDirName; 194 public static String jreFontDirName; 195 private static HashSet<String> missingFontFiles = null; 196 private String defaultFontName; 197 private String defaultFontFileName; 198 protected HashSet<String> registeredFontFiles = new HashSet<>(); 199 200 private ArrayList<String> badFonts; 201 /* fontPath is the location of all fonts on the system, excluding the 202 * JRE's own font directory but including any path specified using the 203 * sun.java2d.fontpath property. Together with that property, it is 204 * initialised by the getPlatformFontPath() method 205 * This call must be followed by a call to registerFontDirs(fontPath) 206 * once any extra debugging path has been appended. 207 */ 208 protected String fontPath; 209 private FontConfiguration fontConfig; 210 /* discoveredAllFonts is set to true when all fonts on the font path are 211 * discovered. This usually also implies opening, validating and 212 * registering, but an implementation may be optimized to avold this. 213 * So see also "loadedAllFontFiles" 214 */ 215 private boolean discoveredAllFonts = false; 216 217 /* No need to keep consing up new instances - reuse a singleton. 218 * The trade-off is that these objects don't get GC'd. 219 */ 220 private static final FilenameFilter ttFilter = new TTFilter(); 221 private static final FilenameFilter t1Filter = new T1Filter(); 222 223 private Font[] allFonts; 224 private String[] allFamilies; // cache for default locale only 225 private Locale lastDefaultLocale; 226 227 public static boolean noType1Font; 228 229 /* Used to indicate required return type from toArray(..); */ 230 private static String[] STR_ARRAY = new String[0]; 231 232 /** 233 * Deprecated, unsupported hack - actually invokes a bug! 234 * Left in for a customer, don't remove. 235 */ 236 private boolean usePlatformFontMetrics = false; 237 238 /** 239 * Returns the global SunFontManager instance. This is similar to 240 * {@link FontManagerFactory#getInstance()} but it returns a 241 * SunFontManager instance instead. This is only used in internal classes 242 * where we can safely assume that a SunFontManager is to be used. 243 * 244 * @return the global SunFontManager instance 245 */ 246 public static SunFontManager getInstance() { 247 FontManager fm = FontManagerFactory.getInstance(); 248 return (SunFontManager) fm; 249 } 250 251 public FilenameFilter getTrueTypeFilter() { 252 return ttFilter; 253 } 254 255 public FilenameFilter getType1Filter() { 256 return t1Filter; 257 } 258 259 static { 260 261 java.security.AccessController.doPrivileged( 262 new java.security.PrivilegedAction<Object>() { 263 264 public Object run() { 265 FontManagerNativeLibrary.load(); 266 267 // JNI throws an exception if a class/method/field is not found, 268 // so there's no need to do anything explicit here. 269 initIDs(); 270 271 switch (StrikeCache.nativeAddressSize) { 272 case 8: longAddresses = true; break; 273 case 4: longAddresses = false; break; 274 default: throw new RuntimeException("Unexpected address size"); 275 } 276 277 noType1Font = 278 "true".equals(System.getProperty("sun.java2d.noType1Font")); 279 jreLibDirName = 280 System.getProperty("java.home","") + File.separator + "lib"; 281 jreFontDirName = jreLibDirName + File.separator + "fonts"; 282 283 return null; 284 } 285 }); 286 } 287 288 /** 289 * If the module image layout changes the location of JDK fonts, 290 * this will be updated to reflect that. 291 */ 292 public static final String getJDKFontDir() { 293 return jreFontDirName; 294 } 295 296 public TrueTypeFont getEUDCFont() { 297 // Overridden in Windows. 298 return null; 299 } 300 301 /* Initialise ptrs used by JNI methods */ 302 private static native void initIDs(); 303 304 @SuppressWarnings("unchecked") 305 protected SunFontManager() { 306 307 java.security.AccessController.doPrivileged( 308 new java.security.PrivilegedAction<Object>() { 309 public Object run() { 310 File badFontFile = 311 new File(jreFontDirName + File.separator + 312 "badfonts.txt"); 313 if (badFontFile.exists()) { 314 FileInputStream fis = null; 315 try { 316 badFonts = new ArrayList<>(); 317 fis = new FileInputStream(badFontFile); 318 InputStreamReader isr = new InputStreamReader(fis); 319 BufferedReader br = new BufferedReader(isr); 320 while (true) { 321 String name = br.readLine(); 322 if (name == null) { 323 break; 324 } else { 325 if (FontUtilities.debugFonts()) { 326 FontUtilities.getLogger().warning("read bad font: " + 327 name); 328 } 329 badFonts.add(name); 330 } 331 } 332 } catch (IOException e) { 333 try { 334 if (fis != null) { 335 fis.close(); 336 } 337 } catch (IOException ioe) { 338 } 339 } 340 } 341 342 /* Here we get the fonts in jre/lib/fonts and register 343 * them so they are always available and preferred over 344 * other fonts. This needs to be registered before the 345 * composite fonts as otherwise some native font that 346 * corresponds may be found as we don't have a way to 347 * handle two fonts of the same name, so the JRE one 348 * must be the first one registered. Pass "true" to 349 * registerFonts method as on-screen these JRE fonts 350 * always go through the JDK rasteriser. 351 */ 352 if (FontUtilities.isLinux) { 353 /* Linux font configuration uses these fonts */ 354 registerFontDir(jreFontDirName); 355 } 356 registerFontsInDir(jreFontDirName, true, Font2D.JRE_RANK, 357 true, false); 358 359 /* Create the font configuration and get any font path 360 * that might be specified. 361 */ 362 fontConfig = createFontConfiguration(); 363 364 String[] fontInfo = getDefaultPlatformFont(); 365 defaultFontName = fontInfo[0]; 366 defaultFontFileName = fontInfo[1]; 367 368 String extraFontPath = fontConfig.getExtraFontPath(); 369 370 /* In prior releases the debugging font path replaced 371 * all normally located font directories except for the 372 * JRE fonts dir. This directory is still always located 373 * and placed at the head of the path but as an 374 * augmentation to the previous behaviour the 375 * changes below allow you to additionally append to 376 * the font path by starting with append: or prepend by 377 * starting with a prepend: sign. Eg: to append 378 * -Dsun.java2d.fontpath=append:/usr/local/myfonts 379 * and to prepend 380 * -Dsun.java2d.fontpath=prepend:/usr/local/myfonts Disp 381 * 382 * If there is an appendedfontpath it in the font 383 * configuration it is used instead of searching the 384 * system for dirs. 385 * The behaviour of append and prepend is then similar 386 * to the normal case. ie it goes after what 387 * you prepend and * before what you append. If the 388 * sun.java2d.fontpath property is used, but it 389 * neither the append or prepend syntaxes is used then 390 * as except for the JRE dir the path is replaced and it 391 * is up to you to make sure that all the right 392 * directories are located. This is platform and 393 * locale-specific so its almost impossible to get 394 * right, so it should be used with caution. 395 */ 396 boolean prependToPath = false; 397 boolean appendToPath = false; 398 String dbgFontPath = 399 System.getProperty("sun.java2d.fontpath"); 400 401 if (dbgFontPath != null) { 402 if (dbgFontPath.startsWith("prepend:")) { 403 prependToPath = true; 404 dbgFontPath = 405 dbgFontPath.substring("prepend:".length()); 406 } else if (dbgFontPath.startsWith("append:")) { 407 appendToPath = true; 408 dbgFontPath = 409 dbgFontPath.substring("append:".length()); 410 } 411 } 412 413 if (FontUtilities.debugFonts()) { 414 PlatformLogger logger = FontUtilities.getLogger(); 415 logger.info("JRE font directory: " + jreFontDirName); 416 logger.info("Extra font path: " + extraFontPath); 417 logger.info("Debug font path: " + dbgFontPath); 418 } 419 420 if (dbgFontPath != null) { 421 /* In debugging mode we register all the paths 422 * Caution: this is a very expensive call on Solaris:- 423 */ 424 fontPath = getPlatformFontPath(noType1Font); 425 426 if (extraFontPath != null) { 427 fontPath = 428 extraFontPath + File.pathSeparator + fontPath; 429 } 430 if (appendToPath) { 431 fontPath = 432 fontPath + File.pathSeparator + dbgFontPath; 433 } else if (prependToPath) { 434 fontPath = 435 dbgFontPath + File.pathSeparator + fontPath; 436 } else { 437 fontPath = dbgFontPath; 438 } 439 registerFontDirs(fontPath); 440 } else if (extraFontPath != null) { 441 /* If the font configuration contains an 442 * "appendedfontpath" entry, it is interpreted as a 443 * set of locations that should always be registered. 444 * It may be additional to locations normally found 445 * for that place, or it may be locations that need 446 * to have all their paths registered to locate all 447 * the needed platform names. 448 * This is typically when the same .TTF file is 449 * referenced from multiple font.dir files and all 450 * of these must be read to find all the native 451 * (XLFD) names for the font, so that X11 font APIs 452 * can be used for as many code points as possible. 453 */ 454 registerFontDirs(extraFontPath); 455 } 456 457 /* On Solaris, we need to register the Japanese TrueType 458 * directory so that we can find the corresponding 459 * bitmap fonts. This could be done by listing the 460 * directory in the font configuration file, but we 461 * don't want to confuse users with this quirk. There 462 * are no bitmap fonts for other writing systems that 463 * correspond to TrueType fonts and have matching XLFDs. 464 * We need to register the bitmap fonts only in 465 * environments where they're on the X font path, i.e., 466 * in the Japanese locale. Note that if the X Toolkit 467 * is in use the font path isn't set up by JDK, but 468 * users of a JA locale should have it 469 * set up already by their login environment. 470 */ 471 if (FontUtilities.isSolaris && Locale.JAPAN.equals(Locale.getDefault())) { 472 registerFontDir("/usr/openwin/lib/locale/ja/X11/fonts/TT"); 473 } 474 475 initCompositeFonts(fontConfig, null); 476 477 return null; 478 } 479 }); 480 481 boolean platformFont = AccessController.doPrivileged( 482 new PrivilegedAction<Boolean>() { 483 public Boolean run() { 484 String prop = 485 System.getProperty("java2d.font.usePlatformFont"); 486 String env = System.getenv("JAVA2D_USEPLATFORMFONT"); 487 return "true".equals(prop) || env != null; 488 } 489 }); 490 491 if (platformFont) { 492 usePlatformFontMetrics = true; 493 System.out.println("Enabling platform font metrics for win32. This is an unsupported option."); 494 System.out.println("This yields incorrect composite font metrics as reported by 1.1.x releases."); 495 System.out.println("It is appropriate only for use by applications which do not use any Java 2"); 496 System.out.println("functionality. This property will be removed in a later release."); 497 } 498 } 499 500 public Font2DHandle getNewComposite(String family, int style, 501 Font2DHandle handle) { 502 503 if (!(handle.font2D instanceof CompositeFont)) { 504 return handle; 505 } 506 507 CompositeFont oldComp = (CompositeFont)handle.font2D; 508 PhysicalFont oldFont = oldComp.getSlotFont(0); 509 510 if (family == null) { 511 family = oldFont.getFamilyName(null); 512 } 513 if (style == -1) { 514 style = oldComp.getStyle(); 515 } 516 517 Font2D newFont = findFont2D(family, style, NO_FALLBACK); 518 if (!(newFont instanceof PhysicalFont)) { 519 newFont = oldFont; 520 } 521 PhysicalFont physicalFont = (PhysicalFont)newFont; 522 CompositeFont dialog2D = 523 (CompositeFont)findFont2D("dialog", style, NO_FALLBACK); 524 if (dialog2D == null) { /* shouldn't happen */ 525 return handle; 526 } 527 CompositeFont compFont = new CompositeFont(physicalFont, dialog2D); 528 Font2DHandle newHandle = new Font2DHandle(compFont); 529 return newHandle; 530 } 531 532 protected void registerCompositeFont(String compositeName, 533 String[] componentFileNames, 534 String[] componentNames, 535 int numMetricsSlots, 536 int[] exclusionRanges, 537 int[] exclusionMaxIndex, 538 boolean defer) { 539 540 CompositeFont cf = new CompositeFont(compositeName, 541 componentFileNames, 542 componentNames, 543 numMetricsSlots, 544 exclusionRanges, 545 exclusionMaxIndex, defer, this); 546 addCompositeToFontList(cf, Font2D.FONT_CONFIG_RANK); 547 synchronized (compFonts) { 548 compFonts[maxCompFont++] = cf; 549 } 550 } 551 552 /* This variant is used only when the application specifies 553 * a variant of composite fonts which prefers locale specific or 554 * proportional fonts. 555 */ 556 protected static void registerCompositeFont(String compositeName, 557 String[] componentFileNames, 558 String[] componentNames, 559 int numMetricsSlots, 560 int[] exclusionRanges, 561 int[] exclusionMaxIndex, 562 boolean defer, 563 ConcurrentHashMap<String, Font2D> 564 altNameCache) { 565 566 CompositeFont cf = new CompositeFont(compositeName, 567 componentFileNames, 568 componentNames, 569 numMetricsSlots, 570 exclusionRanges, 571 exclusionMaxIndex, defer, 572 SunFontManager.getInstance()); 573 574 /* if the cache has an existing composite for this case, make 575 * its handle point to this new font. 576 * This ensures that when the altNameCache that is passed in 577 * is the global mapNameCache - ie we are running as an application - 578 * that any statically created java.awt.Font instances which already 579 * have a Font2D instance will have that re-directed to the new Font 580 * on subsequent uses. This is particularly important for "the" 581 * default font instance, or similar cases where a UI toolkit (eg 582 * Swing) has cached a java.awt.Font. Note that if Swing is using 583 * a custom composite APIs which update the standard composites have 584 * no effect - this is typically the case only when using the Windows 585 * L&F where these APIs would conflict with that L&F anyway. 586 */ 587 Font2D oldFont =altNameCache.get(compositeName.toLowerCase(Locale.ENGLISH)); 588 if (oldFont instanceof CompositeFont) { 589 oldFont.handle.font2D = cf; 590 } 591 altNameCache.put(compositeName.toLowerCase(Locale.ENGLISH), cf); 592 } 593 594 private void addCompositeToFontList(CompositeFont f, int rank) { 595 596 if (FontUtilities.isLogging()) { 597 FontUtilities.getLogger().info("Add to Family "+ f.familyName + 598 ", Font " + f.fullName + " rank="+rank); 599 } 600 f.setRank(rank); 601 compositeFonts.put(f.fullName, f); 602 fullNameToFont.put(f.fullName.toLowerCase(Locale.ENGLISH), f); 603 604 FontFamily family = FontFamily.getFamily(f.familyName); 605 if (family == null) { 606 family = new FontFamily(f.familyName, true, rank); 607 } 608 family.setFont(f, f.style); 609 } 610 611 /* 612 * Systems may have fonts with the same name. 613 * We want to register only one of such fonts (at least until 614 * such time as there might be APIs which can accommodate > 1). 615 * Rank is 1) font configuration fonts, 2) JRE fonts, 3) OT/TT fonts, 616 * 4) Type1 fonts, 5) native fonts. 617 * 618 * If the new font has the same name as the old font, the higher 619 * ranked font gets added, replacing the lower ranked one. 620 * If the fonts are of equal rank, then make a special case of 621 * font configuration rank fonts, which are on closer inspection, 622 * OT/TT fonts such that the larger font is registered. This is 623 * a heuristic since a font may be "larger" in the sense of more 624 * code points, or be a larger "file" because it has more bitmaps. 625 * So it is possible that using filesize may lead to less glyphs, and 626 * using glyphs may lead to lower quality display. Probably number 627 * of glyphs is the ideal, but filesize is information we already 628 * have and is good enough for the known cases. 629 * Also don't want to register fonts that match JRE font families 630 * but are coming from a source other than the JRE. 631 * This will ensure that we will algorithmically style the JRE 632 * plain font and get the same set of glyphs for all styles. 633 * 634 * Note that this method returns a value 635 * if it returns the same object as its argument that means this 636 * font was newly registered. 637 * If it returns a different object it means this font already exists, 638 * and you should use that one. 639 * If it returns null means this font was not registered and none 640 * in that name is registered. The caller must find a substitute 641 */ 642 // MACOSX begin -- need to access this in subclass 643 protected PhysicalFont addToFontList(PhysicalFont f, int rank) { 644 // MACOSX end 645 646 String fontName = f.fullName; 647 String familyName = f.familyName; 648 if (fontName == null || fontName.isEmpty()) { 649 return null; 650 } 651 if (compositeFonts.containsKey(fontName)) { 652 /* Don't register any font that has the same name as a composite */ 653 return null; 654 } 655 f.setRank(rank); 656 if (!physicalFonts.containsKey(fontName)) { 657 if (FontUtilities.isLogging()) { 658 FontUtilities.getLogger().info("Add to Family "+familyName + 659 ", Font " + fontName + " rank="+rank); 660 } 661 physicalFonts.put(fontName, f); 662 FontFamily family = FontFamily.getFamily(familyName); 663 if (family == null) { 664 family = new FontFamily(familyName, false, rank); 665 family.setFont(f, f.style); 666 } else { 667 family.setFont(f, f.style); 668 } 669 fullNameToFont.put(fontName.toLowerCase(Locale.ENGLISH), f); 670 return f; 671 } else { 672 PhysicalFont newFont = f; 673 PhysicalFont oldFont = physicalFonts.get(fontName); 674 if (oldFont == null) { 675 return null; 676 } 677 /* If the new font is of an equal or higher rank, it is a 678 * candidate to replace the current one, subject to further tests. 679 */ 680 if (oldFont.getRank() >= rank) { 681 682 /* All fonts initialise their mapper when first 683 * used. If the mapper is non-null then this font 684 * has been accessed at least once. In that case 685 * do not replace it. This may be overly stringent, 686 * but its probably better not to replace a font that 687 * someone is already using without a compelling reason. 688 * Additionally the primary case where it is known 689 * this behaviour is important is in certain composite 690 * fonts, and since all the components of a given 691 * composite are usually initialised together this 692 * is unlikely. For this to be a problem, there would 693 * have to be a case where two different composites used 694 * different versions of the same-named font, and they 695 * were initialised and used at separate times. 696 * In that case we continue on and allow the new font to 697 * be installed, but replaceFont will continue to allow 698 * the original font to be used in Composite fonts. 699 */ 700 if (oldFont.mapper != null && rank > Font2D.FONT_CONFIG_RANK) { 701 return oldFont; 702 } 703 704 /* Normally we require a higher rank to replace a font, 705 * but as a special case, if the two fonts are the same rank, 706 * and are instances of TrueTypeFont we want the 707 * more complete (larger) one. 708 */ 709 if (oldFont.getRank() == rank) { 710 if (oldFont instanceof TrueTypeFont && 711 newFont instanceof TrueTypeFont) { 712 TrueTypeFont oldTTFont = (TrueTypeFont)oldFont; 713 TrueTypeFont newTTFont = (TrueTypeFont)newFont; 714 if (oldTTFont.fileSize >= newTTFont.fileSize) { 715 return oldFont; 716 } 717 } else { 718 return oldFont; 719 } 720 } 721 /* Don't replace ever JRE fonts. 722 * This test is in case a font configuration references 723 * a Lucida font, which has been mapped to a Lucida 724 * from the host O/S. The assumption here is that any 725 * such font configuration file is probably incorrect, or 726 * the host O/S version is for the use of AWT. 727 * In other words if we reach here, there's a possible 728 * problem with our choice of font configuration fonts. 729 */ 730 if (oldFont.platName.startsWith(jreFontDirName)) { 731 if (FontUtilities.isLogging()) { 732 FontUtilities.getLogger() 733 .warning("Unexpected attempt to replace a JRE " + 734 " font " + fontName + " from " + 735 oldFont.platName + 736 " with " + newFont.platName); 737 } 738 return oldFont; 739 } 740 741 if (FontUtilities.isLogging()) { 742 FontUtilities.getLogger() 743 .info("Replace in Family " + familyName + 744 ",Font " + fontName + " new rank="+rank + 745 " from " + oldFont.platName + 746 " with " + newFont.platName); 747 } 748 replaceFont(oldFont, newFont); 749 physicalFonts.put(fontName, newFont); 750 fullNameToFont.put(fontName.toLowerCase(Locale.ENGLISH), 751 newFont); 752 753 FontFamily family = FontFamily.getFamily(familyName); 754 if (family == null) { 755 family = new FontFamily(familyName, false, rank); 756 family.setFont(newFont, newFont.style); 757 } else { 758 family.setFont(newFont, newFont.style); 759 } 760 return newFont; 761 } else { 762 return oldFont; 763 } 764 } 765 } 766 767 public Font2D[] getRegisteredFonts() { 768 PhysicalFont[] physFonts = getPhysicalFonts(); 769 int mcf = maxCompFont; /* for MT-safety */ 770 Font2D[] regFonts = new Font2D[physFonts.length+mcf]; 771 System.arraycopy(compFonts, 0, regFonts, 0, mcf); 772 System.arraycopy(physFonts, 0, regFonts, mcf, physFonts.length); 773 return regFonts; 774 } 775 776 protected PhysicalFont[] getPhysicalFonts() { 777 return physicalFonts.values().toArray(new PhysicalFont[0]); 778 } 779 780 781 /* The class FontRegistrationInfo is used when a client says not 782 * to register a font immediately. This mechanism is used to defer 783 * initialisation of all the components of composite fonts at JRE 784 * start-up. The CompositeFont class is "aware" of this and when it 785 * is first used it asks for the registration of its components. 786 * Also in the event that any physical font is requested the 787 * deferred fonts are initialised before triggering a search of the 788 * system. 789 * Two maps are used. One to track the deferred fonts. The 790 * other to track the fonts that have been initialised through this 791 * mechanism. 792 */ 793 794 private static final class FontRegistrationInfo { 795 796 String fontFilePath; 797 String[] nativeNames; 798 int fontFormat; 799 boolean javaRasterizer; 800 int fontRank; 801 802 FontRegistrationInfo(String fontPath, String[] names, int format, 803 boolean useJavaRasterizer, int rank) { 804 this.fontFilePath = fontPath; 805 this.nativeNames = names; 806 this.fontFormat = format; 807 this.javaRasterizer = useJavaRasterizer; 808 this.fontRank = rank; 809 } 810 } 811 812 private final ConcurrentHashMap<String, FontRegistrationInfo> 813 deferredFontFiles = 814 new ConcurrentHashMap<String, FontRegistrationInfo>(); 815 private final ConcurrentHashMap<String, Font2DHandle> 816 initialisedFonts = new ConcurrentHashMap<String, Font2DHandle>(); 817 818 /* Remind: possibly enhance initialiseDeferredFonts() to be 819 * optionally given a name and a style and it could stop when it 820 * finds that font - but this would be a problem if two of the 821 * fonts reference the same font face name (cf the Solaris 822 * euro fonts). 823 */ 824 protected synchronized void initialiseDeferredFonts() { 825 for (String fileName : deferredFontFiles.keySet()) { 826 initialiseDeferredFont(fileName); 827 } 828 } 829 830 protected synchronized void registerDeferredJREFonts(String jreDir) { 831 for (FontRegistrationInfo info : deferredFontFiles.values()) { 832 if (info.fontFilePath != null && 833 info.fontFilePath.startsWith(jreDir)) { 834 initialiseDeferredFont(info.fontFilePath); 835 } 836 } 837 } 838 839 public boolean isDeferredFont(String fileName) { 840 return deferredFontFiles.containsKey(fileName); 841 } 842 843 PhysicalFont findJREDeferredFont(String name, int style) { 844 845 /* Iterate over the deferred font files looking for any in the 846 * jre directory that we didn't recognise, open each of these. 847 * In almost all installations this will quickly fall through 848 * because jreOtherFontFiles will be empty. 849 * noOtherJREFontFiles is used so we can skip this block as soon 850 * as its determined that it's not needed - almost always after the 851 * very first time through. 852 */ 853 if (noOtherJREFontFiles) { 854 return null; 855 } 856 synchronized (jreFontDirName) { 857 if (jreOtherFontFiles == null) { 858 HashSet<String> otherFontFiles = new HashSet<String>(); 859 for (String deferredFile : deferredFontFiles.keySet()) { 860 File file = new File(deferredFile); 861 String dir = file.getParent(); 862 String fname = file.getName(); 863 /* skip names which aren't absolute, aren't in the JRE 864 * directory, or are known Lucida fonts. 865 */ 866 if (dir == null || !dir.equals(jreFontDirName)) { 867 continue; 868 } 869 otherFontFiles.add(deferredFile); 870 } 871 jreOtherFontFiles = otherFontFiles.toArray(STR_ARRAY); 872 if (jreOtherFontFiles.length == 0) { 873 noOtherJREFontFiles = true; 874 } 875 } 876 877 for (int i=0; i<jreOtherFontFiles.length;i++) { 878 String fileName = jreOtherFontFiles[i]; 879 if (fileName == null) { 880 continue; 881 } 882 jreOtherFontFiles[i] = null; 883 PhysicalFont physicalFont = initialiseDeferredFont(fileName); 884 if (physicalFont != null && 885 (physicalFont.getFontName(null).equalsIgnoreCase(name) || 886 physicalFont.getFamilyName(null).equalsIgnoreCase(name)) 887 && physicalFont.style == style) { 888 return physicalFont; 889 } 890 } 891 } 892 893 return null; 894 } 895 896 private PhysicalFont findOtherDeferredFont(String name, int style) { 897 for (String fileName : deferredFontFiles.keySet()) { 898 PhysicalFont physicalFont = initialiseDeferredFont(fileName); 899 if (physicalFont != null && 900 (physicalFont.getFontName(null).equalsIgnoreCase(name) || 901 physicalFont.getFamilyName(null).equalsIgnoreCase(name)) && 902 physicalFont.style == style) { 903 return physicalFont; 904 } 905 } 906 return null; 907 } 908 909 private PhysicalFont findDeferredFont(String name, int style) { 910 PhysicalFont physicalFont = findJREDeferredFont(name, style); 911 if (physicalFont != null) { 912 return physicalFont; 913 } else { 914 return findOtherDeferredFont(name, style); 915 } 916 } 917 918 public void registerDeferredFont(String fileNameKey, 919 String fullPathName, 920 String[] nativeNames, 921 int fontFormat, 922 boolean useJavaRasterizer, 923 int fontRank) { 924 FontRegistrationInfo regInfo = 925 new FontRegistrationInfo(fullPathName, nativeNames, fontFormat, 926 useJavaRasterizer, fontRank); 927 deferredFontFiles.put(fileNameKey, regInfo); 928 } 929 930 931 public synchronized 932 PhysicalFont initialiseDeferredFont(String fileNameKey) { 933 934 if (fileNameKey == null) { 935 return null; 936 } 937 if (FontUtilities.isLogging()) { 938 FontUtilities.getLogger() 939 .info("Opening deferred font file " + fileNameKey); 940 } 941 942 PhysicalFont physicalFont; 943 FontRegistrationInfo regInfo = deferredFontFiles.get(fileNameKey); 944 if (regInfo != null) { 945 deferredFontFiles.remove(fileNameKey); 946 physicalFont = registerFontFile(regInfo.fontFilePath, 947 regInfo.nativeNames, 948 regInfo.fontFormat, 949 regInfo.javaRasterizer, 950 regInfo.fontRank); 951 952 953 if (physicalFont != null) { 954 /* Store the handle, so that if a font is bad, we 955 * retrieve the substituted font. 956 */ 957 initialisedFonts.put(fileNameKey, physicalFont.handle); 958 } else { 959 initialisedFonts.put(fileNameKey, 960 getDefaultPhysicalFont().handle); 961 } 962 } else { 963 Font2DHandle handle = initialisedFonts.get(fileNameKey); 964 if (handle == null) { 965 /* Probably shouldn't happen, but just in case */ 966 physicalFont = getDefaultPhysicalFont(); 967 } else { 968 physicalFont = (PhysicalFont)(handle.font2D); 969 } 970 } 971 return physicalFont; 972 } 973 974 public boolean isRegisteredFontFile(String name) { 975 return registeredFonts.containsKey(name); 976 } 977 978 public PhysicalFont getRegisteredFontFile(String name) { 979 return registeredFonts.get(name); 980 } 981 982 /* Note that the return value from this method is not always 983 * derived from this file, and may be null. See addToFontList for 984 * some explanation of this. 985 */ 986 public PhysicalFont registerFontFile(String fileName, 987 String[] nativeNames, 988 int fontFormat, 989 boolean useJavaRasterizer, 990 int fontRank) { 991 992 PhysicalFont regFont = registeredFonts.get(fileName); 993 if (regFont != null) { 994 return regFont; 995 } 996 997 PhysicalFont physicalFont = null; 998 try { 999 String name; 1000 1001 switch (fontFormat) { 1002 1003 case FONTFORMAT_TRUETYPE: 1004 int fn = 0; 1005 TrueTypeFont ttf; 1006 do { 1007 ttf = new TrueTypeFont(fileName, nativeNames, fn++, 1008 useJavaRasterizer); 1009 PhysicalFont pf = addToFontList(ttf, fontRank); 1010 if (physicalFont == null) { 1011 physicalFont = pf; 1012 } 1013 } 1014 while (fn < ttf.getFontCount()); 1015 break; 1016 1017 case FONTFORMAT_TYPE1: 1018 Type1Font t1f = new Type1Font(fileName, nativeNames); 1019 physicalFont = addToFontList(t1f, fontRank); 1020 break; 1021 1022 case FONTFORMAT_NATIVE: 1023 NativeFont nf = new NativeFont(fileName, false); 1024 physicalFont = addToFontList(nf, fontRank); 1025 break; 1026 default: 1027 1028 } 1029 if (FontUtilities.isLogging()) { 1030 FontUtilities.getLogger() 1031 .info("Registered file " + fileName + " as font " + 1032 physicalFont + " rank=" + fontRank); 1033 } 1034 } catch (FontFormatException ffe) { 1035 if (FontUtilities.isLogging()) { 1036 FontUtilities.getLogger().warning("Unusable font: " + 1037 fileName + " " + ffe.toString()); 1038 } 1039 } 1040 if (physicalFont != null && 1041 fontFormat != FONTFORMAT_NATIVE) { 1042 registeredFonts.put(fileName, physicalFont); 1043 } 1044 return physicalFont; 1045 } 1046 1047 public void registerFonts(String[] fileNames, 1048 String[][] nativeNames, 1049 int fontCount, 1050 int fontFormat, 1051 boolean useJavaRasterizer, 1052 int fontRank, boolean defer) { 1053 1054 for (int i=0; i < fontCount; i++) { 1055 if (defer) { 1056 registerDeferredFont(fileNames[i],fileNames[i], nativeNames[i], 1057 fontFormat, useJavaRasterizer, fontRank); 1058 } else { 1059 registerFontFile(fileNames[i], nativeNames[i], 1060 fontFormat, useJavaRasterizer, fontRank); 1061 } 1062 } 1063 } 1064 1065 /* 1066 * This is the Physical font used when some other font on the system 1067 * can't be located. There has to be at least one font or the font 1068 * system is not useful and the graphics environment cannot sustain 1069 * the Java platform. 1070 */ 1071 public PhysicalFont getDefaultPhysicalFont() { 1072 if (defaultPhysicalFont == null) { 1073 /* findFont2D will load all fonts before giving up the search. 1074 * If the JRE Lucida isn't found (eg because the JRE fonts 1075 * directory is missing), it could find another version of Lucida 1076 * from the host system. This is OK because at that point we are 1077 * trying to gracefully handle/recover from a system 1078 * misconfiguration and this is probably a reasonable substitution. 1079 */ 1080 defaultPhysicalFont = (PhysicalFont) 1081 findFont2D(getDefaultFontFaceName(), Font.PLAIN, NO_FALLBACK); 1082 if (defaultPhysicalFont == null) { 1083 /* Because of the findFont2D call above, if we reach here, we 1084 * know all fonts have already been loaded, just accept any 1085 * match at this point. If this fails we are in real trouble 1086 * and I don't know how to recover from there being absolutely 1087 * no fonts anywhere on the system. 1088 */ 1089 Iterator<PhysicalFont> i = physicalFonts.values().iterator(); 1090 if (i.hasNext()) { 1091 defaultPhysicalFont = i.next(); 1092 } else { 1093 throw new Error("Probable fatal error:No fonts found."); 1094 } 1095 } 1096 } 1097 return defaultPhysicalFont; 1098 } 1099 1100 public Font2D getDefaultLogicalFont(int style) { 1101 return findFont2D("dialog", style, NO_FALLBACK); 1102 } 1103 1104 /* 1105 * return String representation of style prepended with "." 1106 * This is useful for performance to avoid unnecessary string operations. 1107 */ 1108 private static String dotStyleStr(int num) { 1109 switch(num){ 1110 case Font.BOLD: 1111 return ".bold"; 1112 case Font.ITALIC: 1113 return ".italic"; 1114 case Font.ITALIC | Font.BOLD: 1115 return ".bolditalic"; 1116 default: 1117 return ".plain"; 1118 } 1119 } 1120 1121 /* This is implemented only on windows and is called from code that 1122 * executes only on windows. This isn't pretty but its not a precedent 1123 * in this file. This very probably should be cleaned up at some point. 1124 */ 1125 protected void 1126 populateFontFileNameMap(HashMap<String,String> fontToFileMap, 1127 HashMap<String,String> fontToFamilyNameMap, 1128 HashMap<String,ArrayList<String>> 1129 familyToFontListMap, 1130 Locale locale) { 1131 } 1132 1133 /* Obtained from Platform APIs (windows only) 1134 * Map from lower-case font full name to basename of font file. 1135 * Eg "arial bold" -> ARIALBD.TTF. 1136 * For TTC files, there is a mapping for each font in the file. 1137 */ 1138 private HashMap<String,String> fontToFileMap = null; 1139 1140 /* Obtained from Platform APIs (windows only) 1141 * Map from lower-case font full name to the name of its font family 1142 * Eg "arial bold" -> "Arial" 1143 */ 1144 private HashMap<String,String> fontToFamilyNameMap = null; 1145 1146 /* Obtained from Platform APIs (windows only) 1147 * Map from a lower-case family name to a list of full names of 1148 * the member fonts, eg: 1149 * "arial" -> ["Arial", "Arial Bold", "Arial Italic","Arial Bold Italic"] 1150 */ 1151 private HashMap<String,ArrayList<String>> familyToFontListMap= null; 1152 1153 /* The directories which contain platform fonts */ 1154 private String[] pathDirs = null; 1155 1156 private boolean haveCheckedUnreferencedFontFiles; 1157 1158 private String[] getFontFilesFromPath(boolean noType1) { 1159 final FilenameFilter filter; 1160 if (noType1) { 1161 filter = ttFilter; 1162 } else { 1163 filter = new TTorT1Filter(); 1164 } 1165 return (String[])AccessController.doPrivileged(new PrivilegedAction<Object>() { 1166 public Object run() { 1167 if (pathDirs.length == 1) { 1168 File dir = new File(pathDirs[0]); 1169 String[] files = dir.list(filter); 1170 if (files == null) { 1171 return new String[0]; 1172 } 1173 for (int f=0; f<files.length; f++) { 1174 files[f] = files[f].toLowerCase(); 1175 } 1176 return files; 1177 } else { 1178 ArrayList<String> fileList = new ArrayList<String>(); 1179 for (int i = 0; i< pathDirs.length; i++) { 1180 File dir = new File(pathDirs[i]); 1181 String[] files = dir.list(filter); 1182 if (files == null) { 1183 continue; 1184 } 1185 for (int f=0; f<files.length ; f++) { 1186 fileList.add(files[f].toLowerCase()); 1187 } 1188 } 1189 return fileList.toArray(STR_ARRAY); 1190 } 1191 } 1192 }); 1193 } 1194 1195 /* This is needed since some windows registry names don't match 1196 * the font names. 1197 * - UPC styled font names have a double space, but the 1198 * registry entry mapping to a file doesn't. 1199 * - Marlett is in a hidden file not listed in the registry 1200 * - The registry advertises that the file david.ttf contains a 1201 * font with the full name "David Regular" when in fact its 1202 * just "David". 1203 * Directly fix up these known cases as this is faster. 1204 * If a font which doesn't match these known cases has no file, 1205 * it may be a font that has been temporarily added to the known set 1206 * or it may be an installed font with a missing registry entry. 1207 * Installed fonts are those in the windows font directories. 1208 * Make a best effort attempt to locate these. 1209 * We obtain the list of TrueType fonts in these directories and 1210 * filter out all the font files we already know about from the registry. 1211 * What remains may be "bad" fonts, duplicate fonts, or perhaps the 1212 * missing font(s) we are looking for. 1213 * Open each of these files to find out. 1214 */ 1215 private void resolveWindowsFonts() { 1216 1217 ArrayList<String> unmappedFontNames = null; 1218 for (String font : fontToFamilyNameMap.keySet()) { 1219 String file = fontToFileMap.get(font); 1220 if (file == null) { 1221 if (font.indexOf(" ") > 0) { 1222 String newName = font.replaceFirst(" ", " "); 1223 file = fontToFileMap.get(newName); 1224 /* If this name exists and isn't for a valid name 1225 * replace the mapping to the file with this font 1226 */ 1227 if (file != null && 1228 !fontToFamilyNameMap.containsKey(newName)) { 1229 fontToFileMap.remove(newName); 1230 fontToFileMap.put(font, file); 1231 } 1232 } else if (font.equals("marlett")) { 1233 fontToFileMap.put(font, "marlett.ttf"); 1234 } else if (font.equals("david")) { 1235 file = fontToFileMap.get("david regular"); 1236 if (file != null) { 1237 fontToFileMap.remove("david regular"); 1238 fontToFileMap.put("david", file); 1239 } 1240 } else { 1241 if (unmappedFontNames == null) { 1242 unmappedFontNames = new ArrayList<String>(); 1243 } 1244 unmappedFontNames.add(font); 1245 } 1246 } 1247 } 1248 1249 if (unmappedFontNames != null) { 1250 HashSet<String> unmappedFontFiles = new HashSet<String>(); 1251 1252 /* Every font key in fontToFileMap ought to correspond to a 1253 * font key in fontToFamilyNameMap. Entries that don't seem 1254 * to correspond are likely fonts that were named differently 1255 * by GDI than in the registry. One known cause of this is when 1256 * Windows has had its regional settings changed so that from 1257 * GDI we get a localised (eg Chinese or Japanese) name for the 1258 * font, but the registry retains the English version of the name 1259 * that corresponded to the "install" locale for windows. 1260 * Since we are in this code block because there are unmapped 1261 * font names, we can look to find unused font->file mappings 1262 * and then open the files to read the names. We don't generally 1263 * want to open font files, as its a performance hit, but this 1264 * occurs only for a small number of fonts on specific system 1265 * configs - ie is believed that a "true" Japanese windows would 1266 * have JA names in the registry too. 1267 * Clone fontToFileMap and remove from the clone all keys which 1268 * match a fontToFamilyNameMap key. What remains maps to the 1269 * files we want to open to find the fonts GDI returned. 1270 * A font in such a file is added to the fontToFileMap after 1271 * checking its one of the unmappedFontNames we are looking for. 1272 * The original name that didn't map is removed from fontToFileMap 1273 * so essentially this "fixes up" fontToFileMap to use the same 1274 * name as GDI. 1275 * Also note that typically the fonts for which this occurs in 1276 * CJK locales are TTC fonts and not all fonts in a TTC may have 1277 * localised names. Eg MSGOTHIC.TTC contains 3 fonts and one of 1278 * them "MS UI Gothic" has no JA name whereas the other two do. 1279 * So not every font in these files is unmapped or new. 1280 */ 1281 @SuppressWarnings("unchecked") 1282 HashMap<String,String> ffmapCopy = 1283 (HashMap<String,String>)(fontToFileMap.clone()); 1284 for (String key : fontToFamilyNameMap.keySet()) { 1285 ffmapCopy.remove(key); 1286 } 1287 for (String key : ffmapCopy.keySet()) { 1288 unmappedFontFiles.add(ffmapCopy.get(key)); 1289 fontToFileMap.remove(key); 1290 } 1291 1292 resolveFontFiles(unmappedFontFiles, unmappedFontNames); 1293 1294 /* If there are still unmapped font names, this means there's 1295 * something that wasn't in the registry. We need to get all 1296 * the font files directly and look at the ones that weren't 1297 * found in the registry. 1298 */ 1299 if (unmappedFontNames.size() > 0) { 1300 1301 /* getFontFilesFromPath() returns all lower case names. 1302 * To compare we also need lower case 1303 * versions of the names from the registry. 1304 */ 1305 ArrayList<String> registryFiles = new ArrayList<String>(); 1306 1307 for (String regFile : fontToFileMap.values()) { 1308 registryFiles.add(regFile.toLowerCase()); 1309 } 1310 /* We don't look for Type1 files here as windows will 1311 * not enumerate these, so aren't useful in reconciling 1312 * GDI's unmapped files. We do find these later when 1313 * we enumerate all fonts. 1314 */ 1315 for (String pathFile : getFontFilesFromPath(true)) { 1316 if (!registryFiles.contains(pathFile)) { 1317 unmappedFontFiles.add(pathFile); 1318 } 1319 } 1320 1321 resolveFontFiles(unmappedFontFiles, unmappedFontNames); 1322 } 1323 1324 /* remove from the set of names that will be returned to the 1325 * user any fonts that can't be mapped to files. 1326 */ 1327 if (unmappedFontNames.size() > 0) { 1328 int sz = unmappedFontNames.size(); 1329 for (int i=0; i<sz; i++) { 1330 String name = unmappedFontNames.get(i); 1331 String familyName = fontToFamilyNameMap.get(name); 1332 if (familyName != null) { 1333 ArrayList<String> family = familyToFontListMap.get(familyName); 1334 if (family != null) { 1335 if (family.size() <= 1) { 1336 familyToFontListMap.remove(familyName); 1337 } 1338 } 1339 } 1340 fontToFamilyNameMap.remove(name); 1341 if (FontUtilities.isLogging()) { 1342 FontUtilities.getLogger() 1343 .info("No file for font:" + name); 1344 } 1345 } 1346 } 1347 } 1348 } 1349 1350 /** 1351 * In some cases windows may have fonts in the fonts folder that 1352 * don't show up in the registry or in the GDI calls to enumerate fonts. 1353 * The only way to find these is to list the directory. We invoke this 1354 * only in getAllFonts/Families, so most searches for a specific 1355 * font that is satisfied by the GDI/registry calls don't take the 1356 * additional hit of listing the directory. This hit is small enough 1357 * that its not significant in these 'enumerate all the fonts' cases. 1358 * The basic approach is to cross-reference the files windows found 1359 * with the ones in the directory listing approach, and for each 1360 * in the latter list that is missing from the former list, register it. 1361 */ 1362 private synchronized void checkForUnreferencedFontFiles() { 1363 if (haveCheckedUnreferencedFontFiles) { 1364 return; 1365 } 1366 haveCheckedUnreferencedFontFiles = true; 1367 if (!FontUtilities.isWindows) { 1368 return; 1369 } 1370 /* getFontFilesFromPath() returns all lower case names. 1371 * To compare we also need lower case 1372 * versions of the names from the registry. 1373 */ 1374 ArrayList<String> registryFiles = new ArrayList<String>(); 1375 for (String regFile : fontToFileMap.values()) { 1376 registryFiles.add(regFile.toLowerCase()); 1377 } 1378 1379 /* To avoid any issues with concurrent modification, create 1380 * copies of the existing maps, add the new fonts into these 1381 * and then replace the references to the old ones with the 1382 * new maps. ConcurrentHashmap is another option but its a lot 1383 * more changes and with this exception, these maps are intended 1384 * to be static. 1385 */ 1386 HashMap<String,String> fontToFileMap2 = null; 1387 HashMap<String,String> fontToFamilyNameMap2 = null; 1388 HashMap<String,ArrayList<String>> familyToFontListMap2 = null;; 1389 1390 for (String pathFile : getFontFilesFromPath(false)) { 1391 if (!registryFiles.contains(pathFile)) { 1392 if (FontUtilities.isLogging()) { 1393 FontUtilities.getLogger() 1394 .info("Found non-registry file : " + pathFile); 1395 } 1396 PhysicalFont f = registerFontFile(getPathName(pathFile)); 1397 if (f == null) { 1398 continue; 1399 } 1400 if (fontToFileMap2 == null) { 1401 fontToFileMap2 = new HashMap<String,String>(fontToFileMap); 1402 fontToFamilyNameMap2 = 1403 new HashMap<String,String>(fontToFamilyNameMap); 1404 familyToFontListMap2 = new 1405 HashMap<String,ArrayList<String>>(familyToFontListMap); 1406 } 1407 String fontName = f.getFontName(null); 1408 String family = f.getFamilyName(null); 1409 String familyLC = family.toLowerCase(); 1410 fontToFamilyNameMap2.put(fontName, family); 1411 fontToFileMap2.put(fontName, pathFile); 1412 ArrayList<String> fonts = familyToFontListMap2.get(familyLC); 1413 if (fonts == null) { 1414 fonts = new ArrayList<String>(); 1415 } else { 1416 fonts = new ArrayList<String>(fonts); 1417 } 1418 fonts.add(fontName); 1419 familyToFontListMap2.put(familyLC, fonts); 1420 } 1421 } 1422 if (fontToFileMap2 != null) { 1423 fontToFileMap = fontToFileMap2; 1424 familyToFontListMap = familyToFontListMap2; 1425 fontToFamilyNameMap = fontToFamilyNameMap2; 1426 } 1427 } 1428 1429 private void resolveFontFiles(HashSet<String> unmappedFiles, 1430 ArrayList<String> unmappedFonts) { 1431 1432 Locale l = SunToolkit.getStartupLocale(); 1433 1434 for (String file : unmappedFiles) { 1435 try { 1436 int fn = 0; 1437 TrueTypeFont ttf; 1438 String fullPath = getPathName(file); 1439 if (FontUtilities.isLogging()) { 1440 FontUtilities.getLogger() 1441 .info("Trying to resolve file " + fullPath); 1442 } 1443 do { 1444 ttf = new TrueTypeFont(fullPath, null, fn++, false); 1445 // prefer the font's locale name. 1446 String fontName = ttf.getFontName(l).toLowerCase(); 1447 if (unmappedFonts.contains(fontName)) { 1448 fontToFileMap.put(fontName, file); 1449 unmappedFonts.remove(fontName); 1450 if (FontUtilities.isLogging()) { 1451 FontUtilities.getLogger() 1452 .info("Resolved absent registry entry for " + 1453 fontName + " located in " + fullPath); 1454 } 1455 } 1456 } 1457 while (fn < ttf.getFontCount()); 1458 } catch (Exception e) { 1459 } 1460 } 1461 } 1462 1463 /* Hardwire the English names and expected file names of fonts 1464 * commonly used at start up. Avoiding until later even the small 1465 * cost of calling platform APIs to locate these can help. 1466 * The code that registers these fonts needs to "bail" if any 1467 * of the files do not exist, so it will verify the existence of 1468 * all non-null file names first. 1469 * They are added in to a map with nominally the first 1470 * word in the name of the family as the key. In all the cases 1471 * we are using the family name is a single word, and as is 1472 * more or less required the family name is the initial sequence 1473 * in a full name. So lookup first finds the matching description, 1474 * then registers the whole family, returning the right font. 1475 */ 1476 public static class FamilyDescription { 1477 public String familyName; 1478 public String plainFullName; 1479 public String boldFullName; 1480 public String italicFullName; 1481 public String boldItalicFullName; 1482 public String plainFileName; 1483 public String boldFileName; 1484 public String italicFileName; 1485 public String boldItalicFileName; 1486 } 1487 1488 static HashMap<String, FamilyDescription> platformFontMap; 1489 1490 /** 1491 * default implementation does nothing. 1492 */ 1493 public HashMap<String, FamilyDescription> populateHardcodedFileNameMap() { 1494 return new HashMap<String, FamilyDescription>(0); 1495 } 1496 1497 Font2D findFontFromPlatformMap(String lcName, int style) { 1498 if (platformFontMap == null) { 1499 platformFontMap = populateHardcodedFileNameMap(); 1500 } 1501 1502 if (platformFontMap == null || platformFontMap.size() == 0) { 1503 return null; 1504 } 1505 1506 int spaceIndex = lcName.indexOf(' '); 1507 String firstWord = lcName; 1508 if (spaceIndex > 0) { 1509 firstWord = lcName.substring(0, spaceIndex); 1510 } 1511 1512 FamilyDescription fd = platformFontMap.get(firstWord); 1513 if (fd == null) { 1514 return null; 1515 } 1516 /* Once we've established that its at least the first word, 1517 * we need to dig deeper to make sure its a match for either 1518 * a full name, or the family name, to make sure its not 1519 * a request for some other font that just happens to start 1520 * with the same first word. 1521 */ 1522 int styleIndex = -1; 1523 if (lcName.equalsIgnoreCase(fd.plainFullName)) { 1524 styleIndex = 0; 1525 } else if (lcName.equalsIgnoreCase(fd.boldFullName)) { 1526 styleIndex = 1; 1527 } else if (lcName.equalsIgnoreCase(fd.italicFullName)) { 1528 styleIndex = 2; 1529 } else if (lcName.equalsIgnoreCase(fd.boldItalicFullName)) { 1530 styleIndex = 3; 1531 } 1532 if (styleIndex == -1 && !lcName.equalsIgnoreCase(fd.familyName)) { 1533 return null; 1534 } 1535 1536 String plainFile = null, boldFile = null, 1537 italicFile = null, boldItalicFile = null; 1538 1539 boolean failure = false; 1540 /* In a terminal server config, its possible that getPathName() 1541 * will return null, if the file doesn't exist, hence the null 1542 * checks on return. But in the normal client config we need to 1543 * follow this up with a check to see if all the files really 1544 * exist for the non-null paths. 1545 */ 1546 getPlatformFontDirs(noType1Font); 1547 1548 if (fd.plainFileName != null) { 1549 plainFile = getPathName(fd.plainFileName); 1550 if (plainFile == null) { 1551 failure = true; 1552 } 1553 } 1554 1555 if (fd.boldFileName != null) { 1556 boldFile = getPathName(fd.boldFileName); 1557 if (boldFile == null) { 1558 failure = true; 1559 } 1560 } 1561 1562 if (fd.italicFileName != null) { 1563 italicFile = getPathName(fd.italicFileName); 1564 if (italicFile == null) { 1565 failure = true; 1566 } 1567 } 1568 1569 if (fd.boldItalicFileName != null) { 1570 boldItalicFile = getPathName(fd.boldItalicFileName); 1571 if (boldItalicFile == null) { 1572 failure = true; 1573 } 1574 } 1575 1576 if (failure) { 1577 if (FontUtilities.isLogging()) { 1578 FontUtilities.getLogger(). 1579 info("Hardcoded file missing looking for " + lcName); 1580 } 1581 platformFontMap.remove(firstWord); 1582 return null; 1583 } 1584 1585 /* Some of these may be null,as not all styles have to exist */ 1586 final String[] files = { 1587 plainFile, boldFile, italicFile, boldItalicFile } ; 1588 1589 failure = java.security.AccessController.doPrivileged( 1590 new java.security.PrivilegedAction<Boolean>() { 1591 public Boolean run() { 1592 for (int i=0; i<files.length; i++) { 1593 if (files[i] == null) { 1594 continue; 1595 } 1596 File f = new File(files[i]); 1597 if (!f.exists()) { 1598 return Boolean.TRUE; 1599 } 1600 } 1601 return Boolean.FALSE; 1602 } 1603 }); 1604 1605 if (failure) { 1606 if (FontUtilities.isLogging()) { 1607 FontUtilities.getLogger(). 1608 info("Hardcoded file missing looking for " + lcName); 1609 } 1610 platformFontMap.remove(firstWord); 1611 return null; 1612 } 1613 1614 /* If we reach here we know that we have all the files we 1615 * expect, so all should be fine so long as the contents 1616 * are what we'd expect. Now on to registering the fonts. 1617 * Currently this code only looks for TrueType fonts, so format 1618 * and rank can be specified without looking at the filename. 1619 */ 1620 Font2D font = null; 1621 for (int f=0;f<files.length;f++) { 1622 if (files[f] == null) { 1623 continue; 1624 } 1625 PhysicalFont pf = 1626 registerFontFile(files[f], null, 1627 FONTFORMAT_TRUETYPE, false, Font2D.TTF_RANK); 1628 if (f == styleIndex) { 1629 font = pf; 1630 } 1631 } 1632 1633 1634 /* Two general cases need a bit more work here. 1635 * 1) If font is null, then it was perhaps a request for a 1636 * non-existent font, such as "Tahoma Italic", or a family name - 1637 * where family and full name of the plain font differ. 1638 * Fall back to finding the closest one in the family. 1639 * This could still fail if a client specified "Segoe" instead of 1640 * "Segoe UI". 1641 * 2) The request is of the form "MyFont Bold", style=Font.ITALIC, 1642 * and so we want to see if there's a Bold Italic font, or 1643 * "MyFamily", style=Font.BOLD, and we may have matched the plain, 1644 * but now need to revise that to the BOLD font. 1645 */ 1646 FontFamily fontFamily = FontFamily.getFamily(fd.familyName); 1647 if (fontFamily != null) { 1648 if (font == null) { 1649 font = fontFamily.getFont(style); 1650 if (font == null) { 1651 font = fontFamily.getClosestStyle(style); 1652 } 1653 } else if (style > 0 && style != font.style) { 1654 style |= font.style; 1655 font = fontFamily.getFont(style); 1656 if (font == null) { 1657 font = fontFamily.getClosestStyle(style); 1658 } 1659 } 1660 } 1661 1662 return font; 1663 } 1664 private synchronized HashMap<String,String> getFullNameToFileMap() { 1665 if (fontToFileMap == null) { 1666 1667 pathDirs = getPlatformFontDirs(noType1Font); 1668 1669 fontToFileMap = new HashMap<String,String>(100); 1670 fontToFamilyNameMap = new HashMap<String,String>(100); 1671 familyToFontListMap = new HashMap<String,ArrayList<String>>(50); 1672 populateFontFileNameMap(fontToFileMap, 1673 fontToFamilyNameMap, 1674 familyToFontListMap, 1675 Locale.ENGLISH); 1676 if (FontUtilities.isWindows) { 1677 resolveWindowsFonts(); 1678 } 1679 if (FontUtilities.isLogging()) { 1680 logPlatformFontInfo(); 1681 } 1682 } 1683 return fontToFileMap; 1684 } 1685 1686 private void logPlatformFontInfo() { 1687 PlatformLogger logger = FontUtilities.getLogger(); 1688 for (int i=0; i< pathDirs.length;i++) { 1689 logger.info("fontdir="+pathDirs[i]); 1690 } 1691 for (String keyName : fontToFileMap.keySet()) { 1692 logger.info("font="+keyName+" file="+ fontToFileMap.get(keyName)); 1693 } 1694 for (String keyName : fontToFamilyNameMap.keySet()) { 1695 logger.info("font="+keyName+" family="+ 1696 fontToFamilyNameMap.get(keyName)); 1697 } 1698 for (String keyName : familyToFontListMap.keySet()) { 1699 logger.info("family="+keyName+ " fonts="+ 1700 familyToFontListMap.get(keyName)); 1701 } 1702 } 1703 1704 /* Note this return list excludes logical fonts and JRE fonts */ 1705 protected String[] getFontNamesFromPlatform() { 1706 if (getFullNameToFileMap().size() == 0) { 1707 return null; 1708 } 1709 checkForUnreferencedFontFiles(); 1710 /* This odd code with TreeMap is used to preserve a historical 1711 * behaviour wrt the sorting order .. */ 1712 ArrayList<String> fontNames = new ArrayList<String>(); 1713 for (ArrayList<String> a : familyToFontListMap.values()) { 1714 for (String s : a) { 1715 fontNames.add(s); 1716 } 1717 } 1718 return fontNames.toArray(STR_ARRAY); 1719 } 1720 1721 public boolean gotFontsFromPlatform() { 1722 return getFullNameToFileMap().size() != 0; 1723 } 1724 1725 public String getFileNameForFontName(String fontName) { 1726 String fontNameLC = fontName.toLowerCase(Locale.ENGLISH); 1727 return fontToFileMap.get(fontNameLC); 1728 } 1729 1730 private PhysicalFont registerFontFile(String file) { 1731 if (new File(file).isAbsolute() && 1732 !registeredFonts.containsKey(file)) { 1733 int fontFormat = FONTFORMAT_NONE; 1734 int fontRank = Font2D.UNKNOWN_RANK; 1735 if (ttFilter.accept(null, file)) { 1736 fontFormat = FONTFORMAT_TRUETYPE; 1737 fontRank = Font2D.TTF_RANK; 1738 } else if 1739 (t1Filter.accept(null, file)) { 1740 fontFormat = FONTFORMAT_TYPE1; 1741 fontRank = Font2D.TYPE1_RANK; 1742 } 1743 if (fontFormat == FONTFORMAT_NONE) { 1744 return null; 1745 } 1746 return registerFontFile(file, null, fontFormat, false, fontRank); 1747 } 1748 return null; 1749 } 1750 1751 /* Used to register any font files that are found by platform APIs 1752 * that weren't previously found in the standard font locations. 1753 * the isAbsolute() check is needed since that's whats stored in the 1754 * set, and on windows, the fonts in the system font directory that 1755 * are in the fontToFileMap are just basenames. We don't want to try 1756 * to register those again, but we do want to register other registry 1757 * installed fonts. 1758 */ 1759 protected void registerOtherFontFiles(HashSet<String> registeredFontFiles) { 1760 if (getFullNameToFileMap().size() == 0) { 1761 return; 1762 } 1763 for (String file : fontToFileMap.values()) { 1764 registerFontFile(file); 1765 } 1766 } 1767 1768 public boolean 1769 getFamilyNamesFromPlatform(TreeMap<String,String> familyNames, 1770 Locale requestedLocale) { 1771 if (getFullNameToFileMap().size() == 0) { 1772 return false; 1773 } 1774 checkForUnreferencedFontFiles(); 1775 for (String name : fontToFamilyNameMap.values()) { 1776 familyNames.put(name.toLowerCase(requestedLocale), name); 1777 } 1778 return true; 1779 } 1780 1781 /* Path may be absolute or a base file name relative to one of 1782 * the platform font directories 1783 */ 1784 private String getPathName(final String s) { 1785 File f = new File(s); 1786 if (f.isAbsolute()) { 1787 return s; 1788 } else if (pathDirs.length==1) { 1789 return pathDirs[0] + File.separator + s; 1790 } else { 1791 String path = java.security.AccessController.doPrivileged( 1792 new java.security.PrivilegedAction<String>() { 1793 public String run() { 1794 for (int p=0; p<pathDirs.length; p++) { 1795 File f = new File(pathDirs[p] +File.separator+ s); 1796 if (f.exists()) { 1797 return f.getAbsolutePath(); 1798 } 1799 } 1800 return null; 1801 } 1802 }); 1803 if (path != null) { 1804 return path; 1805 } 1806 } 1807 return s; // shouldn't happen, but harmless 1808 } 1809 1810 /* lcName is required to be lower case for use as a key. 1811 * lcName may be a full name, or a family name, and style may 1812 * be specified in addition to either of these. So be sure to 1813 * get the right one. Since an app *could* ask for "Foo Regular" 1814 * and later ask for "Foo Italic", if we don't register all the 1815 * styles, then logic in findFont2D may try to style the original 1816 * so we register the entire family if we get a match here. 1817 * This is still a big win because this code is invoked where 1818 * otherwise we would register all fonts. 1819 * It's also useful for the case where "Foo Bold" was specified with 1820 * style Font.ITALIC, as we would want in that case to try to return 1821 * "Foo Bold Italic" if it exists, and it is only by locating "Foo Bold" 1822 * and opening it that we really "know" it's Bold, and can look for 1823 * a font that supports that and the italic style. 1824 * The code in here is not overtly windows-specific but in fact it 1825 * is unlikely to be useful as is on other platforms. It is maintained 1826 * in this shared source file to be close to its sole client and 1827 * because so much of the logic is intertwined with the logic in 1828 * findFont2D. 1829 */ 1830 private Font2D findFontFromPlatform(String lcName, int style) { 1831 if (getFullNameToFileMap().size() == 0) { 1832 return null; 1833 } 1834 1835 ArrayList<String> family = null; 1836 String fontFile = null; 1837 String familyName = fontToFamilyNameMap.get(lcName); 1838 if (familyName != null) { 1839 fontFile = fontToFileMap.get(lcName); 1840 family = familyToFontListMap.get 1841 (familyName.toLowerCase(Locale.ENGLISH)); 1842 } else { 1843 family = familyToFontListMap.get(lcName); // is lcName is a family? 1844 if (family != null && family.size() > 0) { 1845 String lcFontName = family.get(0).toLowerCase(Locale.ENGLISH); 1846 if (lcFontName != null) { 1847 familyName = fontToFamilyNameMap.get(lcFontName); 1848 } 1849 } 1850 } 1851 if (family == null || familyName == null) { 1852 return null; 1853 } 1854 String [] fontList = family.toArray(STR_ARRAY); 1855 if (fontList.length == 0) { 1856 return null; 1857 } 1858 1859 /* first check that for every font in this family we can find 1860 * a font file. The specific reason for doing this is that 1861 * in at least one case on Windows a font has the face name "David" 1862 * but the registry entry is "David Regular". That is the "unique" 1863 * name of the font but in other cases the registry contains the 1864 * "full" name. See the specifications of name ids 3 and 4 in the 1865 * TrueType 'name' table. 1866 * In general this could cause a problem that we fail to register 1867 * if we all members of a family that we may end up mapping to 1868 * the wrong font member: eg return Bold when Plain is needed. 1869 */ 1870 for (int f=0;f<fontList.length;f++) { 1871 String fontNameLC = fontList[f].toLowerCase(Locale.ENGLISH); 1872 String fileName = fontToFileMap.get(fontNameLC); 1873 if (fileName == null) { 1874 if (FontUtilities.isLogging()) { 1875 FontUtilities.getLogger() 1876 .info("Platform lookup : No file for font " + 1877 fontList[f] + " in family " +familyName); 1878 } 1879 return null; 1880 } 1881 } 1882 1883 /* Currently this code only looks for TrueType fonts, so format 1884 * and rank can be specified without looking at the filename. 1885 */ 1886 PhysicalFont physicalFont = null; 1887 if (fontFile != null) { 1888 physicalFont = registerFontFile(getPathName(fontFile), null, 1889 FONTFORMAT_TRUETYPE, false, 1890 Font2D.TTF_RANK); 1891 } 1892 /* Register all fonts in this family. */ 1893 for (int f=0;f<fontList.length;f++) { 1894 String fontNameLC = fontList[f].toLowerCase(Locale.ENGLISH); 1895 String fileName = fontToFileMap.get(fontNameLC); 1896 if (fontFile != null && fontFile.equals(fileName)) { 1897 continue; 1898 } 1899 /* Currently this code only looks for TrueType fonts, so format 1900 * and rank can be specified without looking at the filename. 1901 */ 1902 registerFontFile(getPathName(fileName), null, 1903 FONTFORMAT_TRUETYPE, false, Font2D.TTF_RANK); 1904 } 1905 1906 Font2D font = null; 1907 FontFamily fontFamily = FontFamily.getFamily(familyName); 1908 /* Handle case where request "MyFont Bold", style=Font.ITALIC */ 1909 if (physicalFont != null) { 1910 style |= physicalFont.style; 1911 } 1912 if (fontFamily != null) { 1913 font = fontFamily.getFont(style); 1914 if (font == null) { 1915 font = fontFamily.getClosestStyle(style); 1916 } 1917 } 1918 return font; 1919 } 1920 1921 private ConcurrentHashMap<String, Font2D> fontNameCache = 1922 new ConcurrentHashMap<String, Font2D>(); 1923 1924 /* 1925 * The client supplies a name and a style. 1926 * The name could be a family name, or a full name. 1927 * A font may exist with the specified style, or it may 1928 * exist only in some other style. For non-native fonts the scaler 1929 * may be able to emulate the required style. 1930 */ 1931 public Font2D findFont2D(String name, int style, int fallback) { 1932 String lowerCaseName = name.toLowerCase(Locale.ENGLISH); 1933 String mapName = lowerCaseName + dotStyleStr(style); 1934 1935 /* If preferLocaleFonts() or preferProportionalFonts() has been 1936 * called we may be using an alternate set of composite fonts in this 1937 * app context. The presence of a pre-built name map indicates whether 1938 * this is so, and gives access to the alternate composite for the 1939 * name. 1940 */ 1941 Font2D font = fontNameCache.get(mapName); 1942 if (font != null) { 1943 return font; 1944 } 1945 1946 if (FontUtilities.isLogging()) { 1947 FontUtilities.getLogger().info("Search for font: " + name); 1948 } 1949 1950 // The check below is just so that the bitmap fonts being set by 1951 // AWT and Swing thru the desktop properties do not trigger the 1952 // the load fonts case. The two bitmap fonts are now mapped to 1953 // appropriate equivalents for serif and sansserif. 1954 // Note that the cost of this comparison is only for the first 1955 // call until the map is filled. 1956 if (FontUtilities.isWindows) { 1957 if (lowerCaseName.equals("ms sans serif")) { 1958 name = "sansserif"; 1959 } else if (lowerCaseName.equals("ms serif")) { 1960 name = "serif"; 1961 } 1962 } 1963 1964 /* This isn't intended to support a client passing in the 1965 * string default, but if a client passes in null for the name 1966 * the java.awt.Font class internally substitutes this name. 1967 * So we need to recognise it here to prevent a loadFonts 1968 * on the unrecognised name. The only potential problem with 1969 * this is it would hide any real font called "default"! 1970 * But that seems like a potential problem we can ignore for now. 1971 */ 1972 if (lowerCaseName.equals("default")) { 1973 name = "dialog"; 1974 } 1975 1976 /* First see if its a family name. */ 1977 FontFamily family = FontFamily.getFamily(name); 1978 if (family != null) { 1979 font = family.getFontWithExactStyleMatch(style); 1980 if (font == null) { 1981 font = findDeferredFont(name, style); 1982 } 1983 if (font == null) { 1984 font = findFontFromPlatform(lowerCaseName, style); 1985 } 1986 if (font == null) { 1987 font = family.getFont(style); 1988 } 1989 if (font == null) { 1990 font = family.getClosestStyle(style); 1991 } 1992 if (font != null) { 1993 fontNameCache.put(mapName, font); 1994 return font; 1995 } 1996 } 1997 1998 /* If it wasn't a family name, it should be a full name of 1999 * either a composite, or a physical font 2000 */ 2001 font = fullNameToFont.get(lowerCaseName); 2002 if (font != null) { 2003 /* Check that the requested style matches the matched font's style. 2004 * But also match style automatically if the requested style is 2005 * "plain". This because the existing behaviour is that the fonts 2006 * listed via getAllFonts etc always list their style as PLAIN. 2007 * This does lead to non-commutative behaviours where you might 2008 * start with "Lucida Sans Regular" and ask for a BOLD version 2009 * and get "Lucida Sans DemiBold" but if you ask for the PLAIN 2010 * style of "Lucida Sans DemiBold" you get "Lucida Sans DemiBold". 2011 * This consistent however with what happens if you have a bold 2012 * version of a font and no plain version exists - alg. styling 2013 * doesn't "unbolden" the font. 2014 */ 2015 if (font.style == style || style == Font.PLAIN) { 2016 fontNameCache.put(mapName, font); 2017 return font; 2018 } else { 2019 /* If it was a full name like "Lucida Sans Regular", but 2020 * the style requested is "bold", then we want to see if 2021 * there's the appropriate match against another font in 2022 * that family before trying to load all fonts, or applying a 2023 * algorithmic styling 2024 */ 2025 family = FontFamily.getFamily(font.getFamilyName(null)); 2026 if (family != null) { 2027 Font2D familyFont = family.getFont(style|font.style); 2028 /* We exactly matched the requested style, use it! */ 2029 if (familyFont != null) { 2030 fontNameCache.put(mapName, familyFont); 2031 return familyFont; 2032 } else { 2033 /* This next call is designed to support the case 2034 * where bold italic is requested, and if we must 2035 * style, then base it on either bold or italic - 2036 * not on plain! 2037 */ 2038 familyFont = family.getClosestStyle(style|font.style); 2039 if (familyFont != null) { 2040 /* The next check is perhaps one 2041 * that shouldn't be done. ie if we get this 2042 * far we have probably as close a match as we 2043 * are going to get. We could load all fonts to 2044 * see if somehow some parts of the family are 2045 * loaded but not all of it. 2046 */ 2047 if (familyFont.canDoStyle(style|font.style)) { 2048 fontNameCache.put(mapName, familyFont); 2049 return familyFont; 2050 } 2051 } 2052 } 2053 } 2054 } 2055 } 2056 2057 if (FontUtilities.isWindows) { 2058 2059 font = findFontFromPlatformMap(lowerCaseName, style); 2060 if (FontUtilities.isLogging()) { 2061 FontUtilities.getLogger() 2062 .info("findFontFromPlatformMap returned " + font); 2063 } 2064 if (font != null) { 2065 fontNameCache.put(mapName, font); 2066 return font; 2067 } 2068 /* Don't want Windows to return a font from C:\Windows\Fonts 2069 * if someone has installed a font with the same name 2070 * in the JRE. 2071 */ 2072 if (deferredFontFiles.size() > 0) { 2073 font = findJREDeferredFont(lowerCaseName, style); 2074 if (font != null) { 2075 fontNameCache.put(mapName, font); 2076 return font; 2077 } 2078 } 2079 font = findFontFromPlatform(lowerCaseName, style); 2080 if (font != null) { 2081 if (FontUtilities.isLogging()) { 2082 FontUtilities.getLogger() 2083 .info("Found font via platform API for request:\"" + 2084 name + "\":, style="+style+ 2085 " found font: " + font); 2086 } 2087 fontNameCache.put(mapName, font); 2088 return font; 2089 } 2090 } 2091 2092 /* If reach here and no match has been located, then if there are 2093 * uninitialised deferred fonts, load as many of those as needed 2094 * to find the deferred font. If none is found through that 2095 * search continue on. 2096 * There is possibly a minor issue when more than one 2097 * deferred font implements the same font face. Since deferred 2098 * fonts are only those in font configuration files, this is a 2099 * controlled situation, the known case being Solaris euro_fonts 2100 * versions of Arial, Times New Roman, Courier New. However 2101 * the larger font will transparently replace the smaller one 2102 * - see addToFontList() - when it is needed by the composite font. 2103 */ 2104 if (deferredFontFiles.size() > 0) { 2105 font = findDeferredFont(name, style); 2106 if (font != null) { 2107 fontNameCache.put(mapName, font); 2108 return font; 2109 } 2110 } 2111 2112 /* Some apps use deprecated 1.0 names such as helvetica and courier. On 2113 * Solaris these are Type1 fonts in /usr/openwin/lib/X11/fonts/Type1. 2114 * If running on Solaris will register all the fonts in this 2115 * directory. 2116 * May as well register the whole directory without actually testing 2117 * the font name is one of the deprecated names as the next step would 2118 * load all fonts which are in this directory anyway. 2119 * In the event that this lookup is successful it potentially "hides" 2120 * TrueType versions of such fonts that are elsewhere but since they 2121 * do not exist on Solaris this is not a problem. 2122 * Set a flag to indicate we've done this registration to avoid 2123 * repetition and more seriously, to avoid recursion. 2124 */ 2125 if (FontUtilities.isSolaris &&!loaded1dot0Fonts) { 2126 /* "timesroman" is a special case since that's not the 2127 * name of any known font on Solaris or elsewhere. 2128 */ 2129 if (lowerCaseName.equals("timesroman")) { 2130 font = findFont2D("serif", style, fallback); 2131 fontNameCache.put(mapName, font); 2132 } 2133 register1dot0Fonts(); 2134 loaded1dot0Fonts = true; 2135 Font2D ff = findFont2D(name, style, fallback); 2136 return ff; 2137 } 2138 2139 /* We check for application registered fonts before 2140 * explicitly loading all fonts as if necessary the registration 2141 * code will have done so anyway. And we don't want to needlessly 2142 * load the actual files for all fonts. 2143 * Just as for installed fonts we check for family before fullname. 2144 * We do not add these fonts to fontNameCache for the 2145 * app context case which eliminates the overhead of a per context 2146 * cache for these. 2147 */ 2148 2149 if (fontsAreRegistered) { 2150 Hashtable<String, FontFamily> familyTable = createdByFamilyName; 2151 Hashtable<String, Font2D> nameTable = createdByFullName; 2152 2153 family = familyTable.get(lowerCaseName); 2154 if (family != null) { 2155 font = family.getFontWithExactStyleMatch(style); 2156 if (font == null) { 2157 font = family.getFont(style); 2158 } 2159 if (font == null) { 2160 font = family.getClosestStyle(style); 2161 } 2162 if (font != null) { 2163 if (fontsAreRegistered) { 2164 fontNameCache.put(mapName, font); 2165 } 2166 return font; 2167 } 2168 } 2169 font = nameTable.get(lowerCaseName); 2170 if (font != null) { 2171 if (fontsAreRegistered) { 2172 fontNameCache.put(mapName, font); 2173 } 2174 return font; 2175 } 2176 } 2177 2178 /* If reach here and no match has been located, then if all fonts 2179 * are not yet loaded, do so, and then recurse. 2180 */ 2181 if (!loadedAllFonts) { 2182 if (FontUtilities.isLogging()) { 2183 FontUtilities.getLogger() 2184 .info("Load fonts looking for:" + name); 2185 } 2186 loadFonts(); 2187 loadedAllFonts = true; 2188 return findFont2D(name, style, fallback); 2189 } 2190 2191 if (!loadedAllFontFiles) { 2192 if (FontUtilities.isLogging()) { 2193 FontUtilities.getLogger() 2194 .info("Load font files looking for:" + name); 2195 } 2196 loadFontFiles(); 2197 loadedAllFontFiles = true; 2198 return findFont2D(name, style, fallback); 2199 } 2200 2201 /* The primary name is the locale default - ie not US/English but 2202 * whatever is the default in this locale. This is the way it always 2203 * has been but may be surprising to some developers if "Arial Regular" 2204 * were hard-coded in their app and yet "Arial Regular" was not the 2205 * default name. Fortunately for them, as a consequence of the JDK 2206 * supporting returning names and family names for arbitrary locales, 2207 * we also need to support searching all localised names for a match. 2208 * But because this case of the name used to reference a font is not 2209 * the same as the default for this locale is rare, it makes sense to 2210 * search a much shorter list of default locale names and only go to 2211 * a longer list of names in the event that no match was found. 2212 * So add here code which searches localised names too. 2213 * As in 1.4.x this happens only after loading all fonts, which 2214 * is probably the right order. 2215 */ 2216 if ((font = findFont2DAllLocales(name, style)) != null) { 2217 fontNameCache.put(mapName, font); 2218 return font; 2219 } 2220 2221 /* Perhaps its a "compatibility" name - timesroman, helvetica, 2222 * or courier, which 1.0 apps used for logical fonts. 2223 * We look for these "late" after a loadFonts as we must not 2224 * hide real fonts of these names. 2225 * Map these appropriately: 2226 * On windows this means according to the rules specified by the 2227 * FontConfiguration : do it only for encoding==Cp1252 2228 * 2229 * REMIND: this is something we plan to remove. 2230 */ 2231 if (FontUtilities.isWindows) { 2232 String compatName = 2233 getFontConfiguration().getFallbackFamilyName(name, null); 2234 if (compatName != null) { 2235 font = findFont2D(compatName, style, fallback); 2236 fontNameCache.put(mapName, font); 2237 return font; 2238 } 2239 } else if (lowerCaseName.equals("timesroman")) { 2240 font = findFont2D("serif", style, fallback); 2241 fontNameCache.put(mapName, font); 2242 return font; 2243 } else if (lowerCaseName.equals("helvetica")) { 2244 font = findFont2D("sansserif", style, fallback); 2245 fontNameCache.put(mapName, font); 2246 return font; 2247 } else if (lowerCaseName.equals("courier")) { 2248 font = findFont2D("monospaced", style, fallback); 2249 fontNameCache.put(mapName, font); 2250 return font; 2251 } 2252 2253 if (FontUtilities.isLogging()) { 2254 FontUtilities.getLogger().info("No font found for:" + name); 2255 } 2256 2257 switch (fallback) { 2258 case PHYSICAL_FALLBACK: return getDefaultPhysicalFont(); 2259 case LOGICAL_FALLBACK: return getDefaultLogicalFont(style); 2260 default: return null; 2261 } 2262 } 2263 2264 /* 2265 * Workaround for apps which are dependent on a font metrics bug 2266 * in JDK 1.1. This is an unsupported win32 private setting. 2267 * Left in for a customer - do not remove. 2268 */ 2269 public boolean usePlatformFontMetrics() { 2270 return usePlatformFontMetrics; 2271 } 2272 2273 public int getNumFonts() { 2274 return physicalFonts.size()+maxCompFont; 2275 } 2276 2277 private static boolean fontSupportsEncoding(Font font, String encoding) { 2278 return FontUtilities.getFont2D(font).supportsEncoding(encoding); 2279 } 2280 2281 protected abstract String getFontPath(boolean noType1Fonts); 2282 2283 Thread fileCloser = null; 2284 Vector<File> tmpFontFiles = null; 2285 2286 public Font2D[] createFont2D(File fontFile, int fontFormat, boolean all, 2287 boolean isCopy, CreatedFontTracker tracker) 2288 throws FontFormatException { 2289 2290 List<Font2D> fList = new ArrayList<Font2D>(); 2291 int cnt = 1; 2292 String fontFilePath = fontFile.getPath(); 2293 FileFont font2D = null; 2294 final File fFile = fontFile; 2295 final CreatedFontTracker _tracker = tracker; 2296 try { 2297 switch (fontFormat) { 2298 case Font.TRUETYPE_FONT: 2299 font2D = new TrueTypeFont(fontFilePath, null, 0, true); 2300 fList.add(font2D); 2301 if (!all) { 2302 break; 2303 } 2304 cnt = ((TrueTypeFont)font2D).getFontCount(); 2305 int index = 1; 2306 while (index < cnt) { 2307 fList.add(new TrueTypeFont(fontFilePath, null, index++, true)); 2308 } 2309 break; 2310 case Font.TYPE1_FONT: 2311 font2D = new Type1Font(fontFilePath, null, isCopy); 2312 fList.add(font2D); 2313 break; 2314 default: 2315 throw new FontFormatException("Unrecognised Font Format"); 2316 } 2317 } catch (FontFormatException e) { 2318 if (isCopy) { 2319 java.security.AccessController.doPrivileged( 2320 new java.security.PrivilegedAction<Object>() { 2321 public Object run() { 2322 if (_tracker != null) { 2323 _tracker.subBytes((int)fFile.length()); 2324 } 2325 fFile.delete(); 2326 return null; 2327 } 2328 }); 2329 } 2330 throw(e); 2331 } 2332 if (isCopy) { 2333 FileFont.setFileToRemove(fList, fontFile, cnt, tracker); 2334 synchronized (FontManager.class) { 2335 2336 if (tmpFontFiles == null) { 2337 tmpFontFiles = new Vector<File>(); 2338 } 2339 tmpFontFiles.add(fontFile); 2340 2341 if (fileCloser == null) { 2342 final Runnable fileCloserRunnable = new Runnable() { 2343 public void run() { 2344 java.security.AccessController.doPrivileged( 2345 new java.security.PrivilegedAction<Object>() { 2346 public Object run() { 2347 2348 for (int i=0;i<CHANNELPOOLSIZE;i++) { 2349 if (fontFileCache[i] != null) { 2350 try { 2351 fontFileCache[i].close(); 2352 } catch (Exception e) { 2353 } 2354 } 2355 } 2356 if (tmpFontFiles != null) { 2357 File[] files = new File[tmpFontFiles.size()]; 2358 files = tmpFontFiles.toArray(files); 2359 for (int f=0; f<files.length;f++) { 2360 try { 2361 files[f].delete(); 2362 } catch (Exception e) { 2363 } 2364 } 2365 } 2366 2367 return null; 2368 } 2369 2370 }); 2371 } 2372 }; 2373 AccessController.doPrivileged((PrivilegedAction<Void>) () -> { 2374 ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); 2375 fileCloser = new Thread(rootTG, fileCloserRunnable, 2376 "FileCloser", 0, false); 2377 fileCloser.setContextClassLoader(null); 2378 Runtime.getRuntime().addShutdownHook(fileCloser); 2379 return null; 2380 }); 2381 } 2382 } 2383 } 2384 return fList.toArray(new Font2D[0]); 2385 } 2386 2387 /* remind: used in X11GraphicsEnvironment and called often enough 2388 * that we ought to obsolete this code 2389 */ 2390 public synchronized String getFullNameByFileName(String fileName) { 2391 PhysicalFont[] physFonts = getPhysicalFonts(); 2392 for (int i=0;i<physFonts.length;i++) { 2393 if (physFonts[i].platName.equals(fileName)) { 2394 return (physFonts[i].getFontName(null)); 2395 } 2396 } 2397 return null; 2398 } 2399 2400 /* 2401 * This is called when font is determined to be invalid/bad. 2402 * It designed to be called (for example) by the font scaler 2403 * when in processing a font file it is discovered to be incorrect. 2404 * This is different than the case where fonts are discovered to 2405 * be incorrect during initial verification, as such fonts are 2406 * never registered. 2407 * Handles to this font held are re-directed to a default font. 2408 * This default may not be an ideal substitute buts it better than 2409 * crashing This code assumes a PhysicalFont parameter as it doesn't 2410 * make sense for a Composite to be "bad". 2411 */ 2412 public synchronized void deRegisterBadFont(Font2D font2D) { 2413 if (!(font2D instanceof PhysicalFont)) { 2414 /* We should never reach here, but just in case */ 2415 return; 2416 } else { 2417 if (FontUtilities.isLogging()) { 2418 FontUtilities.getLogger() 2419 .severe("Deregister bad font: " + font2D); 2420 } 2421 replaceFont((PhysicalFont)font2D, getDefaultPhysicalFont()); 2422 } 2423 } 2424 2425 /* 2426 * This encapsulates all the work that needs to be done when a 2427 * Font2D is replaced by a different Font2D. 2428 */ 2429 public synchronized void replaceFont(PhysicalFont oldFont, 2430 PhysicalFont newFont) { 2431 2432 if (oldFont.handle.font2D != oldFont) { 2433 /* already done */ 2434 return; 2435 } 2436 2437 /* If we try to replace the font with itself, that won't work, 2438 * so pick any alternative physical font 2439 */ 2440 if (oldFont == newFont) { 2441 if (FontUtilities.isLogging()) { 2442 FontUtilities.getLogger() 2443 .severe("Can't replace bad font with itself " + oldFont); 2444 } 2445 PhysicalFont[] physFonts = getPhysicalFonts(); 2446 for (int i=0; i<physFonts.length;i++) { 2447 if (physFonts[i] != newFont) { 2448 newFont = physFonts[i]; 2449 break; 2450 } 2451 } 2452 if (oldFont == newFont) { 2453 if (FontUtilities.isLogging()) { 2454 FontUtilities.getLogger() 2455 .severe("This is bad. No good physicalFonts found."); 2456 } 2457 return; 2458 } 2459 } 2460 2461 /* eliminate references to this font, so it won't be located 2462 * by future callers, and will be eligible for GC when all 2463 * references are removed 2464 */ 2465 oldFont.handle.font2D = newFont; 2466 physicalFonts.remove(oldFont.fullName); 2467 fullNameToFont.remove(oldFont.fullName.toLowerCase(Locale.ENGLISH)); 2468 FontFamily.remove(oldFont); 2469 if (localeFullNamesToFont != null) { 2470 Map.Entry<?, ?>[] mapEntries = localeFullNamesToFont.entrySet(). 2471 toArray(new Map.Entry<?, ?>[0]); 2472 /* Should I be replacing these, or just I just remove 2473 * the names from the map? 2474 */ 2475 for (int i=0; i<mapEntries.length;i++) { 2476 if (mapEntries[i].getValue() == oldFont) { 2477 try { 2478 @SuppressWarnings("unchecked") 2479 Map.Entry<String, PhysicalFont> tmp = (Map.Entry<String, PhysicalFont>)mapEntries[i]; 2480 tmp.setValue(newFont); 2481 } catch (Exception e) { 2482 /* some maps don't support this operation. 2483 * In this case just give up and remove the entry. 2484 */ 2485 localeFullNamesToFont.remove(mapEntries[i].getKey()); 2486 } 2487 } 2488 } 2489 } 2490 2491 for (int i=0; i<maxCompFont; i++) { 2492 /* Deferred initialization of composites shouldn't be 2493 * a problem for this case, since a font must have been 2494 * initialised to be discovered to be bad. 2495 * Some JRE composites on Solaris use two versions of the same 2496 * font. The replaced font isn't bad, just "smaller" so there's 2497 * no need to make the slot point to the new font. 2498 * Since composites have a direct reference to the Font2D (not 2499 * via a handle) making this substitution is not safe and could 2500 * cause an additional problem and so this substitution is 2501 * warranted only when a font is truly "bad" and could cause 2502 * a crash. So we now replace it only if its being substituted 2503 * with some font other than a fontconfig rank font 2504 * Since in practice a substitution will have the same rank 2505 * this may never happen, but the code is safer even if its 2506 * also now a no-op. 2507 * The only obvious "glitch" from this stems from the current 2508 * implementation that when asked for the number of glyphs in a 2509 * composite it lies and returns the number in slot 0 because 2510 * composite glyphs aren't contiguous. Since we live with that 2511 * we can live with the glitch that depending on how it was 2512 * initialised a composite may return different values for this. 2513 * Fixing the issues with composite glyph ids is tricky as 2514 * there are exclusion ranges and unlike other fonts even the 2515 * true "numGlyphs" isn't a contiguous range. Likely the only 2516 * solution is an API that returns an array of glyph ranges 2517 * which takes precedence over the existing API. That might 2518 * also need to address excluding ranges which represent a 2519 * code point supported by an earlier component. 2520 */ 2521 if (newFont.getRank() > Font2D.FONT_CONFIG_RANK) { 2522 compFonts[i].replaceComponentFont(oldFont, newFont); 2523 } 2524 } 2525 } 2526 2527 private synchronized void loadLocaleNames() { 2528 if (localeFullNamesToFont != null) { 2529 return; 2530 } 2531 localeFullNamesToFont = new HashMap<String, TrueTypeFont>(); 2532 Font2D[] fonts = getRegisteredFonts(); 2533 for (int i=0; i<fonts.length; i++) { 2534 if (fonts[i] instanceof TrueTypeFont) { 2535 TrueTypeFont ttf = (TrueTypeFont)fonts[i]; 2536 String[] fullNames = ttf.getAllFullNames(); 2537 for (int n=0; n<fullNames.length; n++) { 2538 localeFullNamesToFont.put(fullNames[n], ttf); 2539 } 2540 FontFamily family = FontFamily.getFamily(ttf.familyName); 2541 if (family != null) { 2542 FontFamily.addLocaleNames(family, ttf.getAllFamilyNames()); 2543 } 2544 } 2545 } 2546 } 2547 2548 /* This replicate the core logic of findFont2D but operates on 2549 * all the locale names. This hasn't been merged into findFont2D to 2550 * keep the logic simpler and reduce overhead, since this case is 2551 * almost never used. The main case in which it is called is when 2552 * a bogus font name is used and we need to check all possible names 2553 * before returning the default case. 2554 */ 2555 private Font2D findFont2DAllLocales(String name, int style) { 2556 2557 if (FontUtilities.isLogging()) { 2558 FontUtilities.getLogger() 2559 .info("Searching localised font names for:" + name); 2560 } 2561 2562 /* If reach here and no match has been located, then if we have 2563 * not yet built the map of localeFullNamesToFont for TT fonts, do so 2564 * now. This method must be called after all fonts have been loaded. 2565 */ 2566 if (localeFullNamesToFont == null) { 2567 loadLocaleNames(); 2568 } 2569 String lowerCaseName = name.toLowerCase(); 2570 Font2D font = null; 2571 2572 /* First see if its a family name. */ 2573 FontFamily family = FontFamily.getLocaleFamily(lowerCaseName); 2574 if (family != null) { 2575 font = family.getFont(style); 2576 if (font == null) { 2577 font = family.getClosestStyle(style); 2578 } 2579 if (font != null) { 2580 return font; 2581 } 2582 } 2583 2584 /* If it wasn't a family name, it should be a full name. */ 2585 synchronized (this) { 2586 font = localeFullNamesToFont.get(name); 2587 } 2588 if (font != null) { 2589 if (font.style == style || style == Font.PLAIN) { 2590 return font; 2591 } else { 2592 family = FontFamily.getFamily(font.getFamilyName(null)); 2593 if (family != null) { 2594 Font2D familyFont = family.getFont(style); 2595 /* We exactly matched the requested style, use it! */ 2596 if (familyFont != null) { 2597 return familyFont; 2598 } else { 2599 familyFont = family.getClosestStyle(style); 2600 if (familyFont != null) { 2601 /* The next check is perhaps one 2602 * that shouldn't be done. ie if we get this 2603 * far we have probably as close a match as we 2604 * are going to get. We could load all fonts to 2605 * see if somehow some parts of the family are 2606 * loaded but not all of it. 2607 * This check is commented out for now. 2608 */ 2609 if (!familyFont.canDoStyle(style)) { 2610 familyFont = null; 2611 } 2612 return familyFont; 2613 } 2614 } 2615 } 2616 } 2617 } 2618 return font; 2619 } 2620 2621 /* Supporting "alternate" composite fonts on 2D graphics objects 2622 * is accessed by the application by calling methods on the local 2623 * GraphicsEnvironment. The overall implementation is described 2624 * in one place, here, since otherwise the implementation is spread 2625 * around it may be difficult to track. 2626 * The methods below call into SunGraphicsEnvironment which creates a 2627 * new FontConfiguration instance. The FontConfiguration class, 2628 * and its platform sub-classes are updated to take parameters requesting 2629 * these behaviours. This is then used to create new composite font 2630 * instances. Since this calls the initCompositeFont method in 2631 * SunGraphicsEnvironment it performs the same initialization as is 2632 * performed normally. There may be some duplication of effort, but 2633 * that code is already written to be able to perform properly if called 2634 * to duplicate work. The main difference is that if we detect we are 2635 * running in an applet/browser/Java plugin environment these new fonts 2636 * are not placed in the "default" maps but into an AppContext instance. 2637 * The font lookup mechanism in java.awt.Font.getFont2D() is also updated 2638 * so that look-up for composite fonts will in that case always 2639 * do a lookup rather than returning a cached result. 2640 * This is inefficient but necessary else singleton java.awt.Font 2641 * instances would not retrieve the correct Font2D for the appcontext. 2642 * sun.font.FontManager.findFont2D is also updated to that it uses 2643 * a name map cache specific to that appcontext. 2644 * 2645 * Getting an AppContext is expensive, so there is a global variable 2646 * that records whether these methods have ever been called and can 2647 * avoid the expense for almost all applications. Once the correct 2648 * CompositeFont is associated with the Font, everything should work 2649 * through existing mechanisms. 2650 * A special case is that GraphicsEnvironment.getAllFonts() must 2651 * return an AppContext specific list. 2652 * 2653 * Calling the methods below is "heavyweight" but it is expected that 2654 * these methods will be called very rarely. 2655 * 2656 * If _usingAlternateComposites is true, we are not in an "applet" 2657 * environment and the (single) application has selected 2658 * an alternate composite font behaviour. 2659 * 2660 * - Printing: The implementation delegates logical fonts to an AWT 2661 * mechanism which cannot use these alternate configurations. 2662 * We can detect that alternate fonts are in use and back-off to 2D, but 2663 * that uses outlines. Much of this can be fixed with additional work 2664 * but that may have to wait. The results should be correct, just not 2665 * optimal. 2666 */ 2667 private boolean _usingAlternateComposites = false; 2668 2669 private static boolean gAltJAFont = false; 2670 private boolean gLocalePref = false; 2671 private boolean gPropPref = false; 2672 2673 /* Its used by the FontMetrics caching code which in such 2674 * a case cannot retrieve a cached metrics solely on the basis of 2675 * the Font.equals() method since it needs to also check if the Font2D 2676 * is the same. 2677 * We also use non-standard composites for Swing native L&F fonts on 2678 * Windows. In that case the policy is that the metrics reported are 2679 * based solely on the physical font in the first slot which is the 2680 * visible java.awt.Font. So in that case the metrics cache which tests 2681 * the Font does what we want. In the near future when we expand the GTK 2682 * logical font definitions we may need to revisit this if GTK reports 2683 * combined metrics instead. For now though this test can be simple. 2684 */ 2685 public boolean usingAlternateCompositeFonts() { 2686 return _usingAlternateComposites; 2687 } 2688 2689 /* Modifies the behaviour of a subsequent call to preferLocaleFonts() 2690 * to use Mincho instead of Gothic for dialoginput in JA locales 2691 * on windows. Not needed on other platforms. 2692 */ 2693 public synchronized void useAlternateFontforJALocales() { 2694 if (FontUtilities.isLogging()) { 2695 FontUtilities.getLogger() 2696 .info("Entered useAlternateFontforJALocales()."); 2697 } 2698 if (!FontUtilities.isWindows) { 2699 return; 2700 } 2701 gAltJAFont = true; 2702 } 2703 2704 public boolean usingAlternateFontforJALocales() { 2705 return gAltJAFont; 2706 } 2707 2708 public synchronized void preferLocaleFonts() { 2709 if (FontUtilities.isLogging()) { 2710 FontUtilities.getLogger().info("Entered preferLocaleFonts()."); 2711 } 2712 /* Test if re-ordering will have any effect */ 2713 if (!FontConfiguration.willReorderForStartupLocale()) { 2714 return; 2715 } 2716 if (gLocalePref == true) { 2717 return; 2718 } 2719 gLocalePref = true; 2720 createCompositeFonts(fontNameCache, gLocalePref, gPropPref); 2721 _usingAlternateComposites = true; 2722 } 2723 2724 public synchronized void preferProportionalFonts() { 2725 if (FontUtilities.isLogging()) { 2726 FontUtilities.getLogger() 2727 .info("Entered preferProportionalFonts()."); 2728 } 2729 /* If no proportional fonts are configured, there's no need 2730 * to take any action. 2731 */ 2732 if (!FontConfiguration.hasMonoToPropMap()) { 2733 return; 2734 } 2735 if (gPropPref == true) { 2736 return; 2737 } 2738 gPropPref = true; 2739 createCompositeFonts(fontNameCache, gLocalePref, gPropPref); 2740 _usingAlternateComposites = true; 2741 } 2742 2743 private static HashSet<String> installedNames = null; 2744 private static HashSet<String> getInstalledNames() { 2745 if (installedNames == null) { 2746 Locale l = getSystemStartupLocale(); 2747 SunFontManager fontManager = SunFontManager.getInstance(); 2748 String[] installedFamilies = 2749 fontManager.getInstalledFontFamilyNames(l); 2750 Font[] installedFonts = fontManager.getAllInstalledFonts(); 2751 HashSet<String> names = new HashSet<String>(); 2752 for (int i=0; i<installedFamilies.length; i++) { 2753 names.add(installedFamilies[i].toLowerCase(l)); 2754 } 2755 for (int i=0; i<installedFonts.length; i++) { 2756 names.add(installedFonts[i].getFontName(l).toLowerCase(l)); 2757 } 2758 installedNames = names; 2759 } 2760 return installedNames; 2761 } 2762 2763 private static final Object regFamilyLock = new Object(); 2764 private Hashtable<String,FontFamily> createdByFamilyName; 2765 private Hashtable<String,Font2D> createdByFullName; 2766 private boolean fontsAreRegistered = false; 2767 2768 public boolean registerFont(Font font) { 2769 /* This method should not be called with "null". 2770 * It is the caller's responsibility to ensure that. 2771 */ 2772 if (font == null) { 2773 return false; 2774 } 2775 2776 /* Initialise these objects only once we start to use this API */ 2777 synchronized (regFamilyLock) { 2778 if (createdByFamilyName == null) { 2779 createdByFamilyName = new Hashtable<String,FontFamily>(); 2780 createdByFullName = new Hashtable<String,Font2D>(); 2781 } 2782 } 2783 2784 if (! FontAccess.getFontAccess().isCreatedFont(font)) { 2785 return false; 2786 } 2787 /* We want to ensure that this font cannot override existing 2788 * installed fonts. Check these conditions : 2789 * - family name is not that of an installed font 2790 * - full name is not that of an installed font 2791 * - family name is not the same as the full name of an installed font 2792 * - full name is not the same as the family name of an installed font 2793 * The last two of these may initially look odd but the reason is 2794 * that (unfortunately) Font constructors do not distinuguish these. 2795 * An extreme example of such a problem would be a font which has 2796 * family name "Dialog.Plain" and full name of "Dialog". 2797 * The one arguably overly stringent restriction here is that if an 2798 * application wants to supply a new member of an existing family 2799 * It will get rejected. But since the JRE can perform synthetic 2800 * styling in many cases its not necessary. 2801 * We don't apply the same logic to registered fonts. If apps want 2802 * to do this lets assume they have a reason. It won't cause problems 2803 * except for themselves. 2804 */ 2805 HashSet<String> names = getInstalledNames(); 2806 Locale l = getSystemStartupLocale(); 2807 String familyName = font.getFamily(l).toLowerCase(); 2808 String fullName = font.getFontName(l).toLowerCase(); 2809 if (names.contains(familyName) || names.contains(fullName)) { 2810 return false; 2811 } 2812 2813 /* Checks passed, now register the font */ 2814 Hashtable<String, FontFamily> familyTable = createdByFamilyName; 2815 Hashtable<String, Font2D> fullNameTable = createdByFullName; 2816 fontsAreRegistered = true; 2817 2818 /* Create the FontFamily and add font to the tables */ 2819 Font2D font2D = FontUtilities.getFont2D(font); 2820 int style = font2D.getStyle(); 2821 FontFamily family = familyTable.get(familyName); 2822 if (family == null) { 2823 family = new FontFamily(font.getFamily(l)); 2824 familyTable.put(familyName, family); 2825 } 2826 /* Remove name cache entries if not using app contexts. 2827 * To accommodate a case where code may have registered first a plain 2828 * family member and then used it and is now registering a bold family 2829 * member, we need to remove all members of the family, so that the 2830 * new style can get picked up rather than continuing to synthesise. 2831 */ 2832 if (fontsAreRegistered) { 2833 removeFromCache(family.getFont(Font.PLAIN)); 2834 removeFromCache(family.getFont(Font.BOLD)); 2835 removeFromCache(family.getFont(Font.ITALIC)); 2836 removeFromCache(family.getFont(Font.BOLD|Font.ITALIC)); 2837 removeFromCache(fullNameTable.get(fullName)); 2838 } 2839 family.setFont(font2D, style); 2840 fullNameTable.put(fullName, font2D); 2841 return true; 2842 } 2843 2844 /* Remove from the name cache all references to the Font2D */ 2845 private void removeFromCache(Font2D font) { 2846 if (font == null) { 2847 return; 2848 } 2849 String[] keys = fontNameCache.keySet().toArray(STR_ARRAY); 2850 for (int k=0; k<keys.length;k++) { 2851 if (fontNameCache.get(keys[k]) == font) { 2852 fontNameCache.remove(keys[k]); 2853 } 2854 } 2855 } 2856 2857 // It may look odd to use TreeMap but its more convenient to the caller. 2858 public TreeMap<String, String> getCreatedFontFamilyNames() { 2859 2860 Hashtable<String,FontFamily> familyTable; 2861 if (fontsAreRegistered) { 2862 familyTable = createdByFamilyName; 2863 } else { 2864 return null; 2865 } 2866 2867 Locale l = getSystemStartupLocale(); 2868 synchronized (familyTable) { 2869 TreeMap<String, String> map = new TreeMap<String, String>(); 2870 for (FontFamily f : familyTable.values()) { 2871 Font2D font2D = f.getFont(Font.PLAIN); 2872 if (font2D == null) { 2873 font2D = f.getClosestStyle(Font.PLAIN); 2874 } 2875 String name = font2D.getFamilyName(l); 2876 map.put(name.toLowerCase(l), name); 2877 } 2878 return map; 2879 } 2880 } 2881 2882 public Font[] getCreatedFonts() { 2883 2884 Hashtable<String,Font2D> nameTable; 2885 if (fontsAreRegistered) { 2886 nameTable = createdByFullName; 2887 } else { 2888 return null; 2889 } 2890 2891 Locale l = getSystemStartupLocale(); 2892 synchronized (nameTable) { 2893 Font[] fonts = new Font[nameTable.size()]; 2894 int i=0; 2895 for (Font2D font2D : nameTable.values()) { 2896 fonts[i++] = new Font(font2D.getFontName(l), Font.PLAIN, 1); 2897 } 2898 return fonts; 2899 } 2900 } 2901 2902 2903 protected String[] getPlatformFontDirs(boolean noType1Fonts) { 2904 2905 /* First check if we already initialised path dirs */ 2906 if (pathDirs != null) { 2907 return pathDirs; 2908 } 2909 2910 String path = getPlatformFontPath(noType1Fonts); 2911 StringTokenizer parser = 2912 new StringTokenizer(path, File.pathSeparator); 2913 ArrayList<String> pathList = new ArrayList<String>(); 2914 try { 2915 while (parser.hasMoreTokens()) { 2916 pathList.add(parser.nextToken()); 2917 } 2918 } catch (NoSuchElementException e) { 2919 } 2920 pathDirs = pathList.toArray(new String[0]); 2921 return pathDirs; 2922 } 2923 2924 /** 2925 * Returns an array of two strings. The first element is the 2926 * name of the font. The second element is the file name. 2927 */ 2928 protected abstract String[] getDefaultPlatformFont(); 2929 2930 // Begin: Refactored from SunGraphicsEnviroment. 2931 2932 /* 2933 * helper function for registerFonts 2934 */ 2935 private void addDirFonts(String dirName, File dirFile, 2936 FilenameFilter filter, 2937 int fontFormat, boolean useJavaRasterizer, 2938 int fontRank, 2939 boolean defer, boolean resolveSymLinks) { 2940 String[] ls = dirFile.list(filter); 2941 if (ls == null || ls.length == 0) { 2942 return; 2943 } 2944 String[] fontNames = new String[ls.length]; 2945 String[][] nativeNames = new String[ls.length][]; 2946 int fontCount = 0; 2947 2948 for (int i=0; i < ls.length; i++ ) { 2949 File theFile = new File(dirFile, ls[i]); 2950 String fullName = null; 2951 if (resolveSymLinks) { 2952 try { 2953 fullName = theFile.getCanonicalPath(); 2954 } catch (IOException e) { 2955 } 2956 } 2957 if (fullName == null) { 2958 fullName = dirName + File.separator + ls[i]; 2959 } 2960 2961 // REMIND: case compare depends on platform 2962 if (registeredFontFiles.contains(fullName)) { 2963 continue; 2964 } 2965 2966 if (badFonts != null && badFonts.contains(fullName)) { 2967 if (FontUtilities.debugFonts()) { 2968 FontUtilities.getLogger() 2969 .warning("skip bad font " + fullName); 2970 } 2971 continue; // skip this font file. 2972 } 2973 2974 registeredFontFiles.add(fullName); 2975 2976 if (FontUtilities.debugFonts() 2977 && FontUtilities.getLogger().isLoggable(PlatformLogger.Level.INFO)) { 2978 String message = "Registering font " + fullName; 2979 String[] natNames = getNativeNames(fullName, null); 2980 if (natNames == null) { 2981 message += " with no native name"; 2982 } else { 2983 message += " with native name(s) " + natNames[0]; 2984 for (int nn = 1; nn < natNames.length; nn++) { 2985 message += ", " + natNames[nn]; 2986 } 2987 } 2988 FontUtilities.getLogger().info(message); 2989 } 2990 fontNames[fontCount] = fullName; 2991 nativeNames[fontCount++] = getNativeNames(fullName, null); 2992 } 2993 registerFonts(fontNames, nativeNames, fontCount, fontFormat, 2994 useJavaRasterizer, fontRank, defer); 2995 return; 2996 } 2997 2998 protected String[] getNativeNames(String fontFileName, 2999 String platformName) { 3000 return null; 3001 } 3002 3003 /** 3004 * Returns a file name for the physical font represented by this platform 3005 * font name. The default implementation tries to obtain the file name 3006 * from the font configuration. 3007 * Subclasses may override to provide information from other sources. 3008 */ 3009 protected String getFileNameFromPlatformName(String platformFontName) { 3010 return fontConfig.getFileNameFromPlatformName(platformFontName); 3011 } 3012 3013 /** 3014 * Return the default font configuration. 3015 */ 3016 public FontConfiguration getFontConfiguration() { 3017 return fontConfig; 3018 } 3019 3020 /* A call to this method should be followed by a call to 3021 * registerFontDirs(..) 3022 */ 3023 public String getPlatformFontPath(boolean noType1Font) { 3024 if (fontPath == null) { 3025 fontPath = getFontPath(noType1Font); 3026 } 3027 return fontPath; 3028 } 3029 3030 protected void loadFonts() { 3031 if (discoveredAllFonts) { 3032 return; 3033 } 3034 /* Use lock specific to the font system */ 3035 synchronized (this) { 3036 if (FontUtilities.debugFonts()) { 3037 Thread.dumpStack(); 3038 FontUtilities.getLogger() 3039 .info("SunGraphicsEnvironment.loadFonts() called"); 3040 } 3041 initialiseDeferredFonts(); 3042 3043 java.security.AccessController.doPrivileged( 3044 new java.security.PrivilegedAction<Object>() { 3045 public Object run() { 3046 if (fontPath == null) { 3047 fontPath = getPlatformFontPath(noType1Font); 3048 registerFontDirs(fontPath); 3049 } 3050 if (fontPath != null) { 3051 // this will find all fonts including those already 3052 // registered. But we have checks in place to prevent 3053 // double registration. 3054 if (! gotFontsFromPlatform()) { 3055 registerFontsOnPath(fontPath, false, 3056 Font2D.UNKNOWN_RANK, 3057 false, true); 3058 loadedAllFontFiles = true; 3059 } 3060 } 3061 registerOtherFontFiles(registeredFontFiles); 3062 discoveredAllFonts = true; 3063 return null; 3064 } 3065 }); 3066 } 3067 } 3068 3069 protected void registerFontDirs(String pathName) { 3070 return; 3071 } 3072 3073 private void registerFontsOnPath(String pathName, 3074 boolean useJavaRasterizer, int fontRank, 3075 boolean defer, boolean resolveSymLinks) { 3076 3077 StringTokenizer parser = new StringTokenizer(pathName, 3078 File.pathSeparator); 3079 try { 3080 while (parser.hasMoreTokens()) { 3081 registerFontsInDir(parser.nextToken(), 3082 useJavaRasterizer, fontRank, 3083 defer, resolveSymLinks); 3084 } 3085 } catch (NoSuchElementException e) { 3086 } 3087 } 3088 3089 /* Called to register fall back fonts */ 3090 public void registerFontsInDir(String dirName) { 3091 registerFontsInDir(dirName, true, Font2D.JRE_RANK, true, false); 3092 } 3093 3094 // MACOSX begin -- need to access this in subclass 3095 protected void registerFontsInDir(String dirName, boolean useJavaRasterizer, 3096 // MACOSX end 3097 int fontRank, 3098 boolean defer, boolean resolveSymLinks) { 3099 File pathFile = new File(dirName); 3100 addDirFonts(dirName, pathFile, ttFilter, 3101 FONTFORMAT_TRUETYPE, useJavaRasterizer, 3102 fontRank==Font2D.UNKNOWN_RANK ? 3103 Font2D.TTF_RANK : fontRank, 3104 defer, resolveSymLinks); 3105 addDirFonts(dirName, pathFile, t1Filter, 3106 FONTFORMAT_TYPE1, useJavaRasterizer, 3107 fontRank==Font2D.UNKNOWN_RANK ? 3108 Font2D.TYPE1_RANK : fontRank, 3109 defer, resolveSymLinks); 3110 } 3111 3112 protected void registerFontDir(String path) { 3113 } 3114 3115 /** 3116 * Returns file name for default font, either absolute 3117 * or relative as needed by registerFontFile. 3118 */ 3119 public synchronized String getDefaultFontFile() { 3120 return defaultFontFileName; 3121 } 3122 3123 /** 3124 * Whether registerFontFile expects absolute or relative 3125 * font file names. 3126 */ 3127 protected boolean useAbsoluteFontFileNames() { 3128 return true; 3129 } 3130 3131 /** 3132 * Creates this environment's FontConfiguration. 3133 */ 3134 protected abstract FontConfiguration createFontConfiguration(); 3135 3136 public abstract FontConfiguration 3137 createFontConfiguration(boolean preferLocaleFonts, 3138 boolean preferPropFonts); 3139 3140 /** 3141 * Returns face name for default font, or null if 3142 * no face names are used for CompositeFontDescriptors 3143 * for this platform. 3144 */ 3145 public synchronized String getDefaultFontFaceName() { 3146 return defaultFontName; 3147 } 3148 3149 public void loadFontFiles() { 3150 loadFonts(); 3151 if (loadedAllFontFiles) { 3152 return; 3153 } 3154 /* Use lock specific to the font system */ 3155 synchronized (this) { 3156 if (FontUtilities.debugFonts()) { 3157 Thread.dumpStack(); 3158 FontUtilities.getLogger().info("loadAllFontFiles() called"); 3159 } 3160 java.security.AccessController.doPrivileged( 3161 new java.security.PrivilegedAction<Object>() { 3162 public Object run() { 3163 if (fontPath == null) { 3164 fontPath = getPlatformFontPath(noType1Font); 3165 } 3166 if (fontPath != null) { 3167 // this will find all fonts including those already 3168 // registered. But we have checks in place to prevent 3169 // double registration. 3170 registerFontsOnPath(fontPath, false, 3171 Font2D.UNKNOWN_RANK, 3172 false, true); 3173 } 3174 loadedAllFontFiles = true; 3175 return null; 3176 } 3177 }); 3178 } 3179 } 3180 3181 /* 3182 * This method asks the font configuration API for all platform names 3183 * used as components of composite/logical fonts and iterates over these 3184 * looking up their corresponding file name and registers these fonts. 3185 * It also ensures that the fonts are accessible via platform APIs. 3186 * The composites themselves are then registered. 3187 */ 3188 private void 3189 initCompositeFonts(FontConfiguration fontConfig, 3190 ConcurrentHashMap<String, Font2D> altNameCache) { 3191 3192 if (FontUtilities.isLogging()) { 3193 FontUtilities.getLogger() 3194 .info("Initialising composite fonts"); 3195 } 3196 3197 int numCoreFonts = fontConfig.getNumberCoreFonts(); 3198 String[] fcFonts = fontConfig.getPlatformFontNames(); 3199 for (int f=0; f<fcFonts.length; f++) { 3200 String platformFontName = fcFonts[f]; 3201 String fontFileName = 3202 getFileNameFromPlatformName(platformFontName); 3203 String[] nativeNames = null; 3204 if (fontFileName == null 3205 || fontFileName.equals(platformFontName)) { 3206 /* No file located, so register using the platform name, 3207 * i.e. as a native font. 3208 */ 3209 fontFileName = platformFontName; 3210 } else { 3211 if (f < numCoreFonts) { 3212 /* If platform APIs also need to access the font, add it 3213 * to a set to be registered with the platform too. 3214 * This may be used to add the parent directory to the X11 3215 * font path if its not already there. See the docs for the 3216 * subclass implementation. 3217 * This is now mainly for the benefit of X11-based AWT 3218 * But for historical reasons, 2D initialisation code 3219 * makes these calls. 3220 * If the fontconfiguration file is properly set up 3221 * so that all fonts are mapped to files and all their 3222 * appropriate directories are specified, then this 3223 * method will be low cost as it will return after 3224 * a test that finds a null lookup map. 3225 */ 3226 addFontToPlatformFontPath(platformFontName); 3227 } 3228 nativeNames = getNativeNames(fontFileName, platformFontName); 3229 } 3230 /* Uncomment these two lines to "generate" the XLFD->filename 3231 * mappings needed to speed start-up on Solaris. 3232 * Augment this with the appendedpathname and the mappings 3233 * for native (F3) fonts 3234 */ 3235 //String platName = platformFontName.replaceAll(" ", "_"); 3236 //System.out.println("filename."+platName+"="+fontFileName); 3237 registerFontFile(fontFileName, nativeNames, 3238 Font2D.FONT_CONFIG_RANK, true); 3239 3240 3241 } 3242 /* This registers accumulated paths from the calls to 3243 * addFontToPlatformFontPath(..) and any specified by 3244 * the font configuration. Rather than registering 3245 * the fonts it puts them in a place and form suitable for 3246 * the Toolkit to pick up and use if a toolkit is initialised, 3247 * and if it uses X11 fonts. 3248 */ 3249 registerPlatformFontsUsedByFontConfiguration(); 3250 3251 CompositeFontDescriptor[] compositeFontInfo 3252 = fontConfig.get2DCompositeFontInfo(); 3253 for (int i = 0; i < compositeFontInfo.length; i++) { 3254 CompositeFontDescriptor descriptor = compositeFontInfo[i]; 3255 String[] componentFileNames = descriptor.getComponentFileNames(); 3256 String[] componentFaceNames = descriptor.getComponentFaceNames(); 3257 3258 /* It would be better eventually to handle this in the 3259 * FontConfiguration code which should also remove duplicate slots 3260 */ 3261 if (missingFontFiles != null) { 3262 for (int ii=0; ii<componentFileNames.length; ii++) { 3263 if (missingFontFiles.contains(componentFileNames[ii])) { 3264 componentFileNames[ii] = getDefaultFontFile(); 3265 componentFaceNames[ii] = getDefaultFontFaceName(); 3266 } 3267 } 3268 } 3269 3270 /* FontConfiguration needs to convey how many fonts it has added 3271 * as fallback component fonts which should not affect metrics. 3272 * The core component count will be the number of metrics slots. 3273 * This does not preclude other mechanisms for adding 3274 * fall back component fonts to the composite. 3275 */ 3276 if (altNameCache != null) { 3277 SunFontManager.registerCompositeFont( 3278 descriptor.getFaceName(), 3279 componentFileNames, componentFaceNames, 3280 descriptor.getCoreComponentCount(), 3281 descriptor.getExclusionRanges(), 3282 descriptor.getExclusionRangeLimits(), 3283 true, 3284 altNameCache); 3285 } else { 3286 registerCompositeFont(descriptor.getFaceName(), 3287 componentFileNames, componentFaceNames, 3288 descriptor.getCoreComponentCount(), 3289 descriptor.getExclusionRanges(), 3290 descriptor.getExclusionRangeLimits(), 3291 true); 3292 } 3293 if (FontUtilities.debugFonts()) { 3294 FontUtilities.getLogger() 3295 .info("registered " + descriptor.getFaceName()); 3296 } 3297 } 3298 } 3299 3300 /** 3301 * Notifies graphics environment that the logical font configuration 3302 * uses the given platform font name. The graphics environment may 3303 * use this for platform specific initialization. 3304 */ 3305 protected void addFontToPlatformFontPath(String platformFontName) { 3306 } 3307 3308 protected void registerFontFile(String fontFileName, String[] nativeNames, 3309 int fontRank, boolean defer) { 3310 // REMIND: case compare depends on platform 3311 if (registeredFontFiles.contains(fontFileName)) { 3312 return; 3313 } 3314 int fontFormat; 3315 if (ttFilter.accept(null, fontFileName)) { 3316 fontFormat = FONTFORMAT_TRUETYPE; 3317 } else if (t1Filter.accept(null, fontFileName)) { 3318 fontFormat = FONTFORMAT_TYPE1; 3319 } else { 3320 fontFormat = FONTFORMAT_NATIVE; 3321 } 3322 registeredFontFiles.add(fontFileName); 3323 if (defer) { 3324 registerDeferredFont(fontFileName, fontFileName, nativeNames, 3325 fontFormat, false, fontRank); 3326 } else { 3327 registerFontFile(fontFileName, nativeNames, fontFormat, false, 3328 fontRank); 3329 } 3330 } 3331 3332 protected void registerPlatformFontsUsedByFontConfiguration() { 3333 } 3334 3335 /* 3336 * A GE may verify whether a font file used in a fontconfiguration 3337 * exists. If it doesn't then either we may substitute the default 3338 * font, or perhaps elide it altogether from the composite font. 3339 * This makes some sense on windows where the font file is only 3340 * likely to be in one place. But on other OSes, eg Linux, the file 3341 * can move around depending. So there we probably don't want to assume 3342 * its missing and so won't add it to this list. 3343 * If this list - missingFontFiles - is non-null then the composite 3344 * font initialisation logic tests to see if a font file is in that 3345 * set. 3346 * Only one thread should be able to add to this set so we don't 3347 * synchronize. 3348 */ 3349 protected void addToMissingFontFileList(String fileName) { 3350 if (missingFontFiles == null) { 3351 missingFontFiles = new HashSet<String>(); 3352 } 3353 missingFontFiles.add(fileName); 3354 } 3355 3356 /* 3357 * This is for use only within getAllFonts(). 3358 * Fonts listed in the fontconfig files for windows were all 3359 * on the "deferred" initialisation list. They were registered 3360 * either in the course of the application, or in the call to 3361 * loadFonts() within getAllFonts(). The fontconfig file specifies 3362 * the names of the fonts using the English names. If there's a 3363 * different name in the execution locale, then the platform will 3364 * report that, and we will construct the font with both names, and 3365 * thereby enumerate it twice. This happens for Japanese fonts listed 3366 * in the windows fontconfig, when run in the JA locale. The solution 3367 * is to rely (in this case) on the platform's font->file mapping to 3368 * determine that this name corresponds to a file we already registered. 3369 * This works because 3370 * - we know when we get here all deferred fonts are already initialised 3371 * - when we register a font file, we register all fonts in it. 3372 * - we know the fontconfig fonts are all in the windows registry 3373 */ 3374 private boolean isNameForRegisteredFile(String fontName) { 3375 String fileName = getFileNameForFontName(fontName); 3376 if (fileName == null) { 3377 return false; 3378 } 3379 return registeredFontFiles.contains(fileName); 3380 } 3381 3382 /* 3383 * This invocation is not in a privileged block because 3384 * all privileged operations (reading files and properties) 3385 * was conducted on the creation of the GE 3386 */ 3387 public void 3388 createCompositeFonts(ConcurrentHashMap<String, Font2D> altNameCache, 3389 boolean preferLocale, 3390 boolean preferProportional) { 3391 3392 FontConfiguration fontConfig = 3393 createFontConfiguration(preferLocale, preferProportional); 3394 initCompositeFonts(fontConfig, altNameCache); 3395 } 3396 3397 /** 3398 * Returns all fonts installed in this environment. 3399 */ 3400 public Font[] getAllInstalledFonts() { 3401 if (allFonts == null) { 3402 loadFonts(); 3403 TreeMap<String, Font2D> fontMapNames = new TreeMap<>(); 3404 /* warning: the number of composite fonts could change dynamically 3405 * if applications are allowed to create them. "allfonts" could 3406 * then be stale. 3407 */ 3408 Font2D[] allfonts = getRegisteredFonts(); 3409 for (int i=0; i < allfonts.length; i++) { 3410 if (!(allfonts[i] instanceof NativeFont)) { 3411 fontMapNames.put(allfonts[i].getFontName(null), 3412 allfonts[i]); 3413 } 3414 } 3415 3416 String[] platformNames = getFontNamesFromPlatform(); 3417 if (platformNames != null) { 3418 for (int i=0; i<platformNames.length; i++) { 3419 if (!isNameForRegisteredFile(platformNames[i])) { 3420 fontMapNames.put(platformNames[i], null); 3421 } 3422 } 3423 } 3424 3425 String[] fontNames = null; 3426 if (fontMapNames.size() > 0) { 3427 fontNames = new String[fontMapNames.size()]; 3428 Object [] keyNames = fontMapNames.keySet().toArray(); 3429 for (int i=0; i < keyNames.length; i++) { 3430 fontNames[i] = (String)keyNames[i]; 3431 } 3432 } 3433 Font[] fonts = new Font[fontNames.length]; 3434 for (int i=0; i < fontNames.length; i++) { 3435 fonts[i] = new Font(fontNames[i], Font.PLAIN, 1); 3436 Font2D f2d = fontMapNames.get(fontNames[i]); 3437 if (f2d != null) { 3438 FontAccess.getFontAccess().setFont2D(fonts[i], f2d.handle); 3439 } 3440 } 3441 allFonts = fonts; 3442 } 3443 3444 Font []copyFonts = new Font[allFonts.length]; 3445 System.arraycopy(allFonts, 0, copyFonts, 0, allFonts.length); 3446 return copyFonts; 3447 } 3448 3449 /** 3450 * Get a list of installed fonts in the requested {@link Locale}. 3451 * The list contains the fonts Family Names. 3452 * If Locale is null, the default locale is used. 3453 * 3454 * @param requestedLocale, if null the default locale is used. 3455 * @return list of installed fonts in the system. 3456 */ 3457 public String[] getInstalledFontFamilyNames(Locale requestedLocale) { 3458 if (requestedLocale == null) { 3459 requestedLocale = Locale.getDefault(); 3460 } 3461 if (allFamilies != null && lastDefaultLocale != null && 3462 requestedLocale.equals(lastDefaultLocale)) { 3463 String[] copyFamilies = new String[allFamilies.length]; 3464 System.arraycopy(allFamilies, 0, copyFamilies, 3465 0, allFamilies.length); 3466 return copyFamilies; 3467 } 3468 3469 TreeMap<String,String> familyNames = new TreeMap<String,String>(); 3470 // these names are always there and aren't localised 3471 String str; 3472 str = Font.SERIF; familyNames.put(str.toLowerCase(), str); 3473 str = Font.SANS_SERIF; familyNames.put(str.toLowerCase(), str); 3474 str = Font.MONOSPACED; familyNames.put(str.toLowerCase(), str); 3475 str = Font.DIALOG; familyNames.put(str.toLowerCase(), str); 3476 str = Font.DIALOG_INPUT; familyNames.put(str.toLowerCase(), str); 3477 3478 /* Platform APIs may be used to get the set of available family 3479 * names for the current default locale so long as it is the same 3480 * as the start-up system locale, rather than loading all fonts. 3481 */ 3482 if (requestedLocale.equals(getSystemStartupLocale()) && 3483 getFamilyNamesFromPlatform(familyNames, requestedLocale)) { 3484 /* Augment platform names with JRE font family names */ 3485 getJREFontFamilyNames(familyNames, requestedLocale); 3486 } else { 3487 loadFontFiles(); 3488 Font2D[] physicalfonts = getPhysicalFonts(); 3489 for (int i=0; i < physicalfonts.length; i++) { 3490 if (!(physicalfonts[i] instanceof NativeFont)) { 3491 String name = 3492 physicalfonts[i].getFamilyName(requestedLocale); 3493 familyNames.put(name.toLowerCase(requestedLocale), name); 3494 } 3495 } 3496 } 3497 3498 // Add any native font family names here 3499 addNativeFontFamilyNames(familyNames, requestedLocale); 3500 3501 String[] retval = new String[familyNames.size()]; 3502 Object [] keyNames = familyNames.keySet().toArray(); 3503 for (int i=0; i < keyNames.length; i++) { 3504 retval[i] = familyNames.get(keyNames[i]); 3505 } 3506 if (requestedLocale.equals(Locale.getDefault())) { 3507 lastDefaultLocale = requestedLocale; 3508 allFamilies = new String[retval.length]; 3509 System.arraycopy(retval, 0, allFamilies, 0, allFamilies.length); 3510 } 3511 return retval; 3512 } 3513 3514 // Provides an aperture to add native font family names to the map 3515 protected void addNativeFontFamilyNames(TreeMap<String, String> familyNames, Locale requestedLocale) { } 3516 3517 public void register1dot0Fonts() { 3518 java.security.AccessController.doPrivileged( 3519 new java.security.PrivilegedAction<Object>() { 3520 public Object run() { 3521 String type1Dir = "/usr/openwin/lib/X11/fonts/Type1"; 3522 registerFontsInDir(type1Dir, true, Font2D.TYPE1_RANK, 3523 false, false); 3524 return null; 3525 } 3526 }); 3527 } 3528 3529 /* Really we need only the JRE fonts family names, but there's little 3530 * overhead in doing this the easy way by adding all the currently 3531 * known fonts. 3532 */ 3533 protected void getJREFontFamilyNames(TreeMap<String,String> familyNames, 3534 Locale requestedLocale) { 3535 registerDeferredJREFonts(jreFontDirName); 3536 Font2D[] physicalfonts = getPhysicalFonts(); 3537 for (int i=0; i < physicalfonts.length; i++) { 3538 if (!(physicalfonts[i] instanceof NativeFont)) { 3539 String name = 3540 physicalfonts[i].getFamilyName(requestedLocale); 3541 familyNames.put(name.toLowerCase(requestedLocale), name); 3542 } 3543 } 3544 } 3545 3546 /** 3547 * Default locale can be changed but we need to know the initial locale 3548 * as that is what is used by native code. Changing Java default locale 3549 * doesn't affect that. 3550 * Returns the locale in use when using native code to communicate 3551 * with platform APIs. On windows this is known as the "system" locale, 3552 * and it is usually the same as the platform locale, but not always, 3553 * so this method also checks an implementation property used only 3554 * on windows and uses that if set. 3555 */ 3556 private static Locale systemLocale = null; 3557 private static Locale getSystemStartupLocale() { 3558 if (systemLocale == null) { 3559 systemLocale = (Locale) 3560 java.security.AccessController.doPrivileged( 3561 new java.security.PrivilegedAction<Object>() { 3562 public Object run() { 3563 /* On windows the system locale may be different than the 3564 * user locale. This is an unsupported configuration, but 3565 * in that case we want to return a dummy locale that will 3566 * never cause a match in the usage of this API. This is 3567 * important because Windows documents that the family 3568 * names of fonts are enumerated using the language of 3569 * the system locale. BY returning a dummy locale in that 3570 * case we do not use the platform API which would not 3571 * return us the names we want. 3572 */ 3573 String fileEncoding = System.getProperty("file.encoding", ""); 3574 String sysEncoding = System.getProperty("sun.jnu.encoding"); 3575 if (sysEncoding != null && !sysEncoding.equals(fileEncoding)) { 3576 return Locale.ROOT; 3577 } 3578 3579 String language = System.getProperty("user.language", "en"); 3580 String country = System.getProperty("user.country",""); 3581 String variant = System.getProperty("user.variant",""); 3582 return new Locale(language, country, variant); 3583 } 3584 }); 3585 } 3586 return systemLocale; 3587 } 3588 3589 void addToPool(FileFont font) { 3590 3591 FileFont fontFileToClose = null; 3592 int freeSlot = -1; 3593 3594 synchronized (fontFileCache) { 3595 /* Avoid duplicate entries in the pool, and don't close() it, 3596 * since this method is called only from within open(). 3597 * Seeing a duplicate is most likely to happen if the thread 3598 * was interrupted during a read, forcing perhaps repeated 3599 * close and open calls and it eventually it ends up pointing 3600 * at the same slot. 3601 */ 3602 for (int i=0;i<CHANNELPOOLSIZE;i++) { 3603 if (fontFileCache[i] == font) { 3604 return; 3605 } 3606 if (fontFileCache[i] == null && freeSlot < 0) { 3607 freeSlot = i; 3608 } 3609 } 3610 if (freeSlot >= 0) { 3611 fontFileCache[freeSlot] = font; 3612 return; 3613 } else { 3614 /* replace with new font. */ 3615 fontFileToClose = fontFileCache[lastPoolIndex]; 3616 fontFileCache[lastPoolIndex] = font; 3617 /* lastPoolIndex is updated so that the least recently opened 3618 * file will be closed next. 3619 */ 3620 lastPoolIndex = (lastPoolIndex+1) % CHANNELPOOLSIZE; 3621 } 3622 } 3623 /* Need to close the font file outside of the synchronized block, 3624 * since its possible some other thread is in an open() call on 3625 * this font file, and could be holding its lock and the pool lock. 3626 * Releasing the pool lock allows that thread to continue, so it can 3627 * then release the lock on this font, allowing the close() call 3628 * below to proceed. 3629 * Also, calling close() is safe because any other thread using 3630 * the font we are closing() synchronizes all reading, so we 3631 * will not close the file while its in use. 3632 */ 3633 if (fontFileToClose != null) { 3634 fontFileToClose.close(); 3635 } 3636 } 3637 3638 protected FontUIResource getFontConfigFUIR(String family, int style, 3639 int size) 3640 { 3641 return new FontUIResource(family, style, size); 3642 } 3643 }