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