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