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