rev 60064 : 8248802: Add log helper methods to FontUtilities.java

   1 /*
   2  * Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.awt;
  27 
  28 import java.awt.Font;
  29 import java.io.DataInputStream;
  30 import java.io.DataOutputStream;
  31 import java.io.File;
  32 import java.io.FileInputStream;
  33 import java.io.InputStream;
  34 import java.io.IOException;
  35 import java.io.OutputStream;
  36 import java.nio.charset.Charset;
  37 import java.nio.charset.CharsetEncoder;
  38 import java.security.AccessController;
  39 import java.security.PrivilegedAction;
  40 import java.util.Arrays;
  41 import java.util.HashMap;
  42 import java.util.HashSet;
  43 import java.util.Hashtable;
  44 import java.util.Locale;
  45 import java.util.Map.Entry;
  46 import java.util.Properties;
  47 import java.util.Set;
  48 import java.util.Vector;
  49 import sun.font.CompositeFontDescriptor;
  50 import sun.font.SunFontManager;
  51 import sun.font.FontManagerFactory;
  52 import sun.font.FontUtilities;
  53 import sun.util.logging.PlatformLogger;
  54 
  55 /**
  56  * Provides the definitions of the five logical fonts: Serif, SansSerif,
  57  * Monospaced, Dialog, and DialogInput. The necessary information
  58  * is obtained from fontconfig files.
  59  */
  60 public abstract class FontConfiguration {
  61 
  62     //static global runtime env
  63     protected static String osVersion;
  64     protected static String osName;
  65     protected static String encoding; // canonical name of default nio charset
  66     protected static Locale startupLocale = null;
  67     protected static Hashtable<String, String> localeMap = null;
  68     private static FontConfiguration fontConfig;
  69     private static PlatformLogger logger;
  70     protected static boolean isProperties = true;
  71 
  72     protected SunFontManager fontManager;
  73     protected boolean preferLocaleFonts;
  74     protected boolean preferPropFonts;
  75 
  76     private File fontConfigFile;
  77     private boolean foundOsSpecificFile;
  78     private boolean inited;
  79     private String javaLib;
  80 
  81     /* A default FontConfiguration must be created before an alternate
  82      * one to ensure proper static initialisation takes place.
  83      */
  84     public FontConfiguration(SunFontManager fm) {
  85         if (FontUtilities.debugFonts()) {
  86             FontUtilities.getLogger()
  87                 .info("Creating standard Font Configuration");
  88         }
  89         if (FontUtilities.debugFonts() && logger == null) {
  90             logger = PlatformLogger.getLogger("sun.awt.FontConfiguration");
  91         }
  92         fontManager = fm;
  93         setOsNameAndVersion();  /* static initialization */
  94         setEncoding();          /* static initialization */
  95         /* Separating out the file location from the rest of the
  96          * initialisation, so the caller has the option of doing
  97          * something else if a suitable file isn't found.
  98          */
  99         findFontConfigFile();
 100     }
 101 
 102     public synchronized boolean init() {
 103         if (!inited) {
 104             this.preferLocaleFonts = false;
 105             this.preferPropFonts = false;
 106             setFontConfiguration();
 107             readFontConfigFile(fontConfigFile);
 108             initFontConfig();
 109             inited = true;
 110         }
 111         return true;
 112     }
 113 
 114     public FontConfiguration(SunFontManager fm,
 115                              boolean preferLocaleFonts,
 116                              boolean preferPropFonts) {
 117         fontManager = fm;
 118         if (FontUtilities.debugFonts()) {
 119             FontUtilities.getLogger()
 120                 .info("Creating alternate Font Configuration");
 121         }
 122         this.preferLocaleFonts = preferLocaleFonts;
 123         this.preferPropFonts = preferPropFonts;
 124         /* fontConfig should be initialised by default constructor, and
 125          * its data tables can be shared, since readFontConfigFile doesn't
 126          * update any other state. Also avoid a doPrivileged block.
 127          */
 128         initFontConfig();
 129     }
 130 
 131     /**
 132      * Fills in this instance's osVersion and osName members. By
 133      * default uses the system properties os.name and os.version;
 134      * subclasses may override.
 135      */
 136     protected void setOsNameAndVersion() {
 137         osName = System.getProperty("os.name");
 138         osVersion = System.getProperty("os.version");
 139     }
 140 
 141     private void setEncoding() {
 142         encoding = Charset.defaultCharset().name();
 143         startupLocale = SunToolkit.getStartupLocale();
 144     }
 145 
 146     /////////////////////////////////////////////////////////////////////
 147     // methods for loading the FontConfig file                         //
 148     /////////////////////////////////////////////////////////////////////
 149 
 150     public boolean foundOsSpecificFile() {
 151         return foundOsSpecificFile;
 152     }
 153 
 154     /* Smoke test to see if we can trust this configuration by testing if
 155      * the first slot of a composite font maps to an installed file.
 156      */
 157     public boolean fontFilesArePresent() {
 158         init();
 159         short fontNameID = compFontNameIDs[0][0][0];
 160         short fileNameID = getComponentFileID(fontNameID);
 161         final String fileName = mapFileName(getComponentFileName(fileNameID));
 162         Boolean exists = java.security.AccessController.doPrivileged(
 163             new java.security.PrivilegedAction<Boolean>() {
 164                  public Boolean run() {
 165                      try {
 166                          File f = new File(fileName);
 167                          return Boolean.valueOf(f.exists());
 168                      }
 169                      catch (Exception e) {
 170                          return Boolean.FALSE;
 171                      }
 172                  }
 173                 });
 174         return exists.booleanValue();
 175     }
 176 
 177     private void findFontConfigFile() {
 178 
 179         foundOsSpecificFile = true; // default assumption.
 180         String javaHome = System.getProperty("java.home");
 181         if (javaHome == null) {
 182             throw new Error("java.home property not set");
 183         }
 184         javaLib = javaHome + File.separator + "lib";
 185         String javaConfFonts = javaHome +
 186                                File.separator + "conf" +
 187                                File.separator + "fonts";
 188         String userConfigFile = System.getProperty("sun.awt.fontconfig");
 189         if (userConfigFile != null) {
 190             fontConfigFile = new File(userConfigFile);
 191         } else {
 192             fontConfigFile = findFontConfigFile(javaConfFonts);
 193             if (fontConfigFile == null) {
 194                 fontConfigFile = findFontConfigFile(javaLib);
 195             }
 196         }
 197     }
 198 
 199     private void readFontConfigFile(File f) {
 200         /* This is invoked here as readFontConfigFile is only invoked
 201          * once per VM, and always in a privileged context, thus the
 202          * directory containing installed fall back fonts is accessed
 203          * from this context
 204          */
 205         getInstalledFallbackFonts(javaLib);
 206 
 207         if (f != null) {
 208             try {
 209                 FileInputStream in = new FileInputStream(f.getPath());
 210                 if (isProperties) {
 211                     loadProperties(in);
 212                 } else {
 213                     loadBinary(in);
 214                 }
 215                 in.close();
 216                 if (FontUtilities.debugFonts()) {
 217                     logger.config("Read logical font configuration from " + f);
 218                 }
 219             } catch (IOException e) {
 220                 if (FontUtilities.debugFonts()) {
 221                     logger.config("Failed to read logical font configuration from " + f);
 222                 }
 223             }
 224         }
 225         String version = getVersion();
 226         if (!"1".equals(version) && FontUtilities.debugFonts()) {
 227             logger.config("Unsupported fontconfig version: " + version);
 228         }
 229     }
 230 
 231     protected void getInstalledFallbackFonts(String javaLib) {
 232         String fallbackDirName = javaLib + File.separator +
 233             "fonts" + File.separator + "fallback";
 234 
 235         File fallbackDir = new File(fallbackDirName);
 236         if (fallbackDir.exists() && fallbackDir.isDirectory()) {
 237             String[] ttfs = fallbackDir.list(fontManager.getTrueTypeFilter());
 238             String[] t1s = fallbackDir.list(fontManager.getType1Filter());
 239             int numTTFs = (ttfs == null) ? 0 : ttfs.length;
 240             int numT1s = (t1s == null) ? 0 : t1s.length;
 241             int len = numTTFs + numT1s;
 242             if (numTTFs + numT1s == 0) {
 243                 return;
 244             }
 245             installedFallbackFontFiles = new String[len];
 246             for (int i=0; i<numTTFs; i++) {
 247                 installedFallbackFontFiles[i] =
 248                     fallbackDir + File.separator + ttfs[i];
 249             }
 250             for (int i=0; i<numT1s; i++) {
 251                 installedFallbackFontFiles[i+numTTFs] =
 252                     fallbackDir + File.separator + t1s[i];
 253             }
 254             fontManager.registerFontsInDir(fallbackDirName);
 255         }
 256     }
 257 
 258     private File findImpl(String fname) {
 259         File f = new File(fname + ".properties");
 260         if (FontUtilities.debugFonts()) {
 261             logger.info("Looking for text fontconfig file : " + f);
 262         }
 263         if (f.canRead()) {
 264             if (FontUtilities.debugFonts()) {
 265                 logger.info("Found file : " + f);
 266             }
 267             isProperties = true;
 268             return f;
 269         }
 270         f = new File(fname + ".bfc");
 271         if (FontUtilities.debugFonts()) {
 272             logger.info("Looking for binary fontconfig file : " + f);
 273         }
 274         if (f.canRead()) {
 275             if (FontUtilities.debugFonts()) {
 276                 logger.info("Found file : " + f);
 277             }
 278             isProperties = false;
 279             return f;
 280         }
 281         return null;
 282     }
 283 
 284     private File findFontConfigFile(String dir) {
 285         if (!(new File(dir)).exists()) {
 286             return null;
 287         }
 288         String baseName = dir + File.separator + "fontconfig";
 289         File configFile;
 290         String osMajorVersion = null;
 291         if (osVersion != null && osName != null) {
 292             configFile = findImpl(baseName + "." + osName + "." + osVersion);
 293             if (configFile != null) {
 294                 return configFile;
 295             }
 296             int decimalPointIndex = osVersion.indexOf('.');
 297             if (decimalPointIndex != -1) {
 298                 osMajorVersion = osVersion.substring(0, osVersion.indexOf('.'));
 299                 configFile = findImpl(baseName + "." + osName + "." + osMajorVersion);
 300                 if (configFile != null) {
 301                     return configFile;
 302                 }
 303             }
 304         }
 305         if (osName != null) {
 306             configFile = findImpl(baseName + "." + osName);
 307             if (configFile != null) {
 308                 return configFile;
 309             }
 310         }
 311         if (osVersion != null) {
 312             configFile = findImpl(baseName + "." + osVersion);
 313             if (configFile != null) {
 314                 return configFile;
 315             }
 316             if (osMajorVersion != null) {
 317                 configFile = findImpl(baseName + "." + osMajorVersion);
 318                 if (configFile != null) {
 319                     return configFile;
 320                 }
 321             }
 322         }
 323         foundOsSpecificFile = false;
 324 
 325         configFile = findImpl(baseName);
 326         if (configFile != null) {
 327             return configFile;
 328         }
 329         if (FontUtilities.debugFonts()) {
 330             logger.info("Did not find a fontconfig file.");
 331         }
 332         return null;
 333     }
 334 
 335     /* Initialize the internal data tables from binary format font
 336      * configuration file.
 337      */
 338     public static void loadBinary(InputStream inStream) throws IOException {
 339         DataInputStream in = new DataInputStream(inStream);
 340         head = readShortTable(in, HEAD_LENGTH);
 341         int[] tableSizes = new int[INDEX_TABLEEND];
 342         for (int i = 0; i < INDEX_TABLEEND; i++) {
 343             tableSizes[i] = head[i + 1] - head[i];
 344         }
 345         table_scriptIDs       = readShortTable(in, tableSizes[INDEX_scriptIDs]);
 346         table_scriptFonts     = readShortTable(in, tableSizes[INDEX_scriptFonts]);
 347         table_elcIDs          = readShortTable(in, tableSizes[INDEX_elcIDs]);
 348         table_sequences        = readShortTable(in, tableSizes[INDEX_sequences]);
 349         table_fontfileNameIDs = readShortTable(in, tableSizes[INDEX_fontfileNameIDs]);
 350         table_componentFontNameIDs = readShortTable(in, tableSizes[INDEX_componentFontNameIDs]);
 351         table_filenames       = readShortTable(in, tableSizes[INDEX_filenames]);
 352         table_awtfontpaths    = readShortTable(in, tableSizes[INDEX_awtfontpaths]);
 353         table_exclusions      = readShortTable(in, tableSizes[INDEX_exclusions]);
 354         table_proportionals   = readShortTable(in, tableSizes[INDEX_proportionals]);
 355         table_scriptFontsMotif   = readShortTable(in, tableSizes[INDEX_scriptFontsMotif]);
 356         table_alphabeticSuffix   = readShortTable(in, tableSizes[INDEX_alphabeticSuffix]);
 357         table_stringIDs       = readShortTable(in, tableSizes[INDEX_stringIDs]);
 358 
 359         //StringTable cache
 360         stringCache = new String[table_stringIDs.length + 1];
 361 
 362         int len = tableSizes[INDEX_stringTable];
 363         byte[] bb = new byte[len * 2];
 364         table_stringTable = new char[len];
 365         in.read(bb);
 366         int i = 0, j = 0;
 367         while (i < len) {
 368            table_stringTable[i++] = (char)(bb[j++] << 8 | (bb[j++] & 0xff));
 369         }
 370         if (verbose) {
 371             dump();
 372         }
 373     }
 374 
 375     /* Generate a binary format font configuration from internal data
 376      * tables.
 377      */
 378     public static void saveBinary(OutputStream out) throws IOException {
 379         sanityCheck();
 380 
 381         DataOutputStream dataOut = new DataOutputStream(out);
 382         writeShortTable(dataOut, head);
 383         writeShortTable(dataOut, table_scriptIDs);
 384         writeShortTable(dataOut, table_scriptFonts);
 385         writeShortTable(dataOut, table_elcIDs);
 386         writeShortTable(dataOut, table_sequences);
 387         writeShortTable(dataOut, table_fontfileNameIDs);
 388         writeShortTable(dataOut, table_componentFontNameIDs);
 389         writeShortTable(dataOut, table_filenames);
 390         writeShortTable(dataOut, table_awtfontpaths);
 391         writeShortTable(dataOut, table_exclusions);
 392         writeShortTable(dataOut, table_proportionals);
 393         writeShortTable(dataOut, table_scriptFontsMotif);
 394         writeShortTable(dataOut, table_alphabeticSuffix);
 395         writeShortTable(dataOut, table_stringIDs);
 396         //stringTable
 397         dataOut.writeChars(new String(table_stringTable));
 398         out.close();
 399         if (verbose) {
 400             dump();
 401         }
 402     }
 403 
 404     //private static boolean loadingProperties;
 405     private static short stringIDNum;
 406     private static short[] stringIDs;
 407     private static StringBuilder stringTable;
 408 
 409     public static void loadProperties(InputStream in) throws IOException {
 410         //loadingProperties = true;
 411         //StringID starts from "1", "0" is reserved for "not defined"
 412         stringIDNum = 1;
 413         stringIDs = new short[1000];
 414         stringTable = new StringBuilder(4096);
 415 
 416         if (verbose && logger == null) {
 417             logger = PlatformLogger.getLogger("sun.awt.FontConfiguration");
 418         }
 419         new PropertiesHandler().load(in);
 420 
 421         //loadingProperties = false;
 422         stringIDs = null;
 423         stringTable = null;
 424     }
 425 
 426 
 427     /////////////////////////////////////////////////////////////////////
 428     // methods for initializing the FontConfig                         //
 429     /////////////////////////////////////////////////////////////////////
 430 
 431     /**
 432      *  set initLocale, initEncoding and initELC for this FontConfig object
 433      *  currently we just simply use the startup locale and encoding
 434      */
 435     private void initFontConfig() {
 436         initLocale = startupLocale;
 437         initEncoding = encoding;
 438         if (preferLocaleFonts && !willReorderForStartupLocale()) {
 439             preferLocaleFonts = false;
 440         }
 441         initELC = getInitELC();
 442         initAllComponentFonts();
 443     }
 444 
 445     //"ELC" stands for "Encoding.Language.Country". This method returns
 446     //the ID of the matched elc setting of "initLocale" in elcIDs table.
 447     //If no match is found, it returns the default ID, which is
 448     //"NULL.NULL.NULL" in elcIDs table.
 449     private short getInitELC() {
 450         if (initELC != -1) {
 451             return initELC;
 452         }
 453         HashMap <String, Integer> elcIDs = new HashMap<String, Integer>();
 454         for (int i = 0; i < table_elcIDs.length; i++) {
 455             elcIDs.put(getString(table_elcIDs[i]), i);
 456         }
 457         String language = initLocale.getLanguage();
 458         String country = initLocale.getCountry();
 459         String elc;
 460         if (elcIDs.containsKey(elc=initEncoding + "." + language + "." + country)
 461             || elcIDs.containsKey(elc=initEncoding + "." + language)
 462             || elcIDs.containsKey(elc=initEncoding)) {
 463             initELC = elcIDs.get(elc).shortValue();
 464         } else {
 465             initELC = elcIDs.get("NULL.NULL.NULL").shortValue();
 466         }
 467         int i = 0;
 468         while (i < table_alphabeticSuffix.length) {
 469             if (initELC == table_alphabeticSuffix[i]) {
 470                 alphabeticSuffix = getString(table_alphabeticSuffix[i + 1]);
 471                 return initELC;
 472             }
 473             i += 2;
 474         }
 475         return initELC;
 476     }
 477 
 478     public static boolean verbose;
 479     private short    initELC = -1;
 480     private Locale   initLocale;
 481     private String   initEncoding;
 482     private String   alphabeticSuffix;
 483 
 484     private short[][][] compFontNameIDs = new short[NUM_FONTS][NUM_STYLES][];
 485     private int[][][] compExclusions = new int[NUM_FONTS][][];
 486     private int[] compCoreNum = new int[NUM_FONTS];
 487 
 488     private Set<Short> coreFontNameIDs = new HashSet<Short>();
 489     private Set<Short> fallbackFontNameIDs = new HashSet<Short>();
 490 
 491     private void initAllComponentFonts() {
 492         short[] fallbackScripts = getFallbackScripts();
 493         for (int fontIndex = 0; fontIndex < NUM_FONTS; fontIndex++) {
 494             short[] coreScripts = getCoreScripts(fontIndex);
 495             compCoreNum[fontIndex] = coreScripts.length;
 496             /*
 497             System.out.println("coreScriptID=" + table_sequences[initELC * 5 + fontIndex]);
 498             for (int i = 0; i < coreScripts.length; i++) {
 499             System.out.println("  " + i + " :" + getString(table_scriptIDs[coreScripts[i]]));
 500             }
 501             */
 502             //init exclusionRanges
 503             int[][] exclusions = new int[coreScripts.length][];
 504             for (int i = 0; i < coreScripts.length; i++) {
 505                 exclusions[i] = getExclusionRanges(coreScripts[i]);
 506             }
 507             compExclusions[fontIndex] = exclusions;
 508             //init componentFontNames
 509             for (int styleIndex = 0; styleIndex < NUM_STYLES; styleIndex++) {
 510                 int index;
 511                 short[] nameIDs = new short[coreScripts.length + fallbackScripts.length];
 512                 //core
 513                 for (index = 0; index < coreScripts.length; index++) {
 514                     nameIDs[index] = getComponentFontID(coreScripts[index],
 515                                                fontIndex, styleIndex);
 516                     if (preferLocaleFonts && localeMap != null &&
 517                             fontManager.usingAlternateFontforJALocales()) {
 518                         nameIDs[index] = remapLocaleMap(fontIndex, styleIndex,
 519                                                         coreScripts[index], nameIDs[index]);
 520                     }
 521                     if (preferPropFonts) {
 522                         nameIDs[index] = remapProportional(fontIndex, nameIDs[index]);
 523                     }
 524                     //System.out.println("nameid=" + nameIDs[index]);
 525                     coreFontNameIDs.add(nameIDs[index]);
 526                 }
 527                 //fallback
 528                 for (int i = 0; i < fallbackScripts.length; i++) {
 529                     short id = getComponentFontID(fallbackScripts[i],
 530                                                fontIndex, styleIndex);
 531                     if (preferLocaleFonts && localeMap != null &&
 532                             fontManager.usingAlternateFontforJALocales()) {
 533                         id = remapLocaleMap(fontIndex, styleIndex, fallbackScripts[i], id);
 534                     }
 535                     if (preferPropFonts) {
 536                         id = remapProportional(fontIndex, id);
 537                     }
 538                     if (contains(nameIDs, id, index)) {
 539                         continue;
 540                     }
 541                     /*
 542                       System.out.println("fontIndex=" + fontIndex + ", styleIndex=" + styleIndex
 543                            + ", fbIndex=" + i + ",fbS=" + fallbackScripts[i] + ", id=" + id);
 544                     */
 545                     fallbackFontNameIDs.add(id);
 546                     nameIDs[index++] = id;
 547                 }
 548                 if (index < nameIDs.length) {
 549                     short[] newNameIDs = new short[index];
 550                     System.arraycopy(nameIDs, 0, newNameIDs, 0, index);
 551                     nameIDs = newNameIDs;
 552                 }
 553                 compFontNameIDs[fontIndex][styleIndex] = nameIDs;
 554             }
 555         }
 556    }
 557 
 558    private short remapLocaleMap(int fontIndex, int styleIndex, short scriptID, short fontID) {
 559         String scriptName = getString(table_scriptIDs[scriptID]);
 560 
 561         String value = localeMap.get(scriptName);
 562         if (value == null) {
 563             String fontName = fontNames[fontIndex];
 564             String styleName = styleNames[styleIndex];
 565             value = localeMap.get(fontName + "." + styleName + "." + scriptName);
 566         }
 567         if (value == null) {
 568             return fontID;
 569         }
 570 
 571         for (int i = 0; i < table_componentFontNameIDs.length; i++) {
 572             String name = getString(table_componentFontNameIDs[i]);
 573             if (value.equalsIgnoreCase(name)) {
 574                 fontID = (short)i;
 575                 break;
 576             }
 577         }
 578         return fontID;
 579     }
 580 
 581     public static boolean hasMonoToPropMap() {
 582         return table_proportionals != null && table_proportionals.length != 0;
 583     }
 584 
 585     private short remapProportional(int fontIndex, short id) {
 586     if (preferPropFonts &&
 587         table_proportionals.length != 0 &&
 588         fontIndex != 2 &&         //"monospaced"
 589         fontIndex != 4) {         //"dialoginput"
 590             int i = 0;
 591             while (i < table_proportionals.length) {
 592                 if (table_proportionals[i] == id) {
 593                     return table_proportionals[i + 1];
 594                 }
 595                 i += 2;
 596             }
 597         }
 598         return id;
 599     }
 600 
 601     /////////////////////////////////////////////////////////////////////
 602     // Methods for handling font and style names                       //
 603     /////////////////////////////////////////////////////////////////////
 604     protected static final int NUM_FONTS = 5;
 605     protected static final int NUM_STYLES = 4;
 606     protected static final String[] fontNames
 607             = {"serif", "sansserif", "monospaced", "dialog", "dialoginput"};
 608     protected static final String[] publicFontNames
 609             = {Font.SERIF, Font.SANS_SERIF, Font.MONOSPACED, Font.DIALOG,
 610                Font.DIALOG_INPUT};
 611     protected static final String[] styleNames
 612             = {"plain", "bold", "italic", "bolditalic"};
 613 
 614     /**
 615      * Checks whether the given font family name is a valid logical font name.
 616      * The check is case insensitive.
 617      */
 618     public static boolean isLogicalFontFamilyName(String fontName) {
 619         return isLogicalFontFamilyNameLC(fontName.toLowerCase(Locale.ENGLISH));
 620     }
 621 
 622     /**
 623      * Checks whether the given font family name is a valid logical font name.
 624      * The check is case sensitive.
 625      */
 626     public static boolean isLogicalFontFamilyNameLC(String fontName) {
 627         for (int i = 0; i < fontNames.length; i++) {
 628             if (fontName.equals(fontNames[i])) {
 629                 return true;
 630             }
 631         }
 632         return false;
 633     }
 634 
 635     /**
 636      * Checks whether the given style name is a valid logical font style name.
 637      */
 638     private static boolean isLogicalFontStyleName(String styleName) {
 639         for (int i = 0; i < styleNames.length; i++) {
 640             if (styleName.equals(styleNames[i])) {
 641                 return true;
 642             }
 643         }
 644         return false;
 645     }
 646 
 647     /**
 648      * Checks whether the given font face name is a valid logical font name.
 649      * The check is case insensitive.
 650      */
 651     public static boolean isLogicalFontFaceName(String fontName) {
 652         return isLogicalFontFaceNameLC(fontName.toLowerCase(Locale.ENGLISH));
 653     }
 654 
 655    /**
 656     * Checks whether the given font face name is a valid logical font name.
 657     * The check is case sensitive.
 658     */
 659     public static boolean isLogicalFontFaceNameLC(String fontName) {
 660         int period = fontName.indexOf('.');
 661         if (period >= 0) {
 662             String familyName = fontName.substring(0, period);
 663             String styleName = fontName.substring(period + 1);
 664             return isLogicalFontFamilyName(familyName) &&
 665                     isLogicalFontStyleName(styleName);
 666         } else {
 667             return isLogicalFontFamilyName(fontName);
 668         }
 669     }
 670 
 671     protected static int getFontIndex(String fontName) {
 672         return getArrayIndex(fontNames, fontName);
 673     }
 674 
 675     protected static int getStyleIndex(String styleName) {
 676         return getArrayIndex(styleNames, styleName);
 677     }
 678 
 679     private static int getArrayIndex(String[] names, String name) {
 680         for (int i = 0; i < names.length; i++) {
 681             if (name.equals(names[i])) {
 682                 return i;
 683             }
 684         }
 685         assert false;
 686         return 0;
 687     }
 688 
 689     protected static int getStyleIndex(int style) {
 690         switch (style) {
 691             case Font.PLAIN:
 692                 return 0;
 693             case Font.BOLD:
 694                 return 1;
 695             case Font.ITALIC:
 696                 return 2;
 697             case Font.BOLD | Font.ITALIC:
 698                 return 3;
 699             default:
 700                 return 0;
 701         }
 702     }
 703 
 704     protected static String getFontName(int fontIndex) {
 705         return fontNames[fontIndex];
 706     }
 707 
 708     protected static String getStyleName(int styleIndex) {
 709         return styleNames[styleIndex];
 710     }
 711 
 712     /**
 713      * Returns the font face name for the given logical font
 714      * family name and style.
 715      * The style argument is interpreted as in java.awt.Font.Font.
 716      */
 717     public static String getLogicalFontFaceName(String familyName, int style) {
 718         assert isLogicalFontFamilyName(familyName);
 719         return familyName.toLowerCase(Locale.ENGLISH) + "." + getStyleString(style);
 720     }
 721 
 722     /**
 723      * Returns the string typically used in properties files
 724      * for the given style.
 725      * The style argument is interpreted as in java.awt.Font.Font.
 726      */
 727     public static String getStyleString(int style) {
 728         return getStyleName(getStyleIndex(style));
 729     }
 730 
 731     /**
 732      * Returns a fallback name for the given font name. For a few known
 733      * font names, matching logical font names are returned. For all
 734      * other font names, defaultFallback is returned.
 735      * defaultFallback differs between AWT and 2D.
 736      */
 737     public abstract String getFallbackFamilyName(String fontName, String defaultFallback);
 738 
 739     /**
 740      * Returns the 1.1 equivalent for some old 1.0 font family names for
 741      * which we need to maintain compatibility in some configurations.
 742      * Returns null for other font names.
 743      */
 744     protected String getCompatibilityFamilyName(String fontName) {
 745         fontName = fontName.toLowerCase(Locale.ENGLISH);
 746         if (fontName.equals("timesroman")) {
 747             return "serif";
 748         } else if (fontName.equals("helvetica")) {
 749             return "sansserif";
 750         } else if (fontName.equals("courier")) {
 751             return "monospaced";
 752         }
 753         return null;
 754     }
 755 
 756     protected static String[] installedFallbackFontFiles = null;
 757 
 758     /**
 759      * Maps a file name given in the font configuration file
 760      * to a format appropriate for the platform.
 761      */
 762     protected String mapFileName(String fileName) {
 763         return fileName;
 764     }
 765 
 766     //////////////////////////////////////////////////////////////////////
 767     //  reordering                                                      //
 768     //////////////////////////////////////////////////////////////////////
 769 
 770     /* Mappings from file encoding to font config name for font supporting
 771      * the corresponding language. This is filled in by initReorderMap()
 772      */
 773     protected HashMap<String, Object> reorderMap = null;
 774 
 775     /* Platform-specific mappings */
 776     protected abstract void initReorderMap();
 777 
 778     /* Move item at index "src" to "dst", shuffling all values in
 779      * between down
 780      */
 781     private void shuffle(String[] seq, int src, int dst) {
 782         if (dst >= src) {
 783             return;
 784         }
 785         String tmp = seq[src];
 786         for (int i=src; i>dst; i--) {
 787             seq[i] = seq[i-1];
 788         }
 789         seq[dst] = tmp;
 790     }
 791 
 792     /* Called to determine if there's a re-order sequence for this locale/
 793      * encoding. If there's none then the caller can "bail" and avoid
 794      * unnecessary work
 795      */
 796     public static boolean willReorderForStartupLocale() {
 797         return getReorderSequence() != null;
 798     }
 799 
 800     private static Object getReorderSequence() {
 801         if (fontConfig.reorderMap == null) {
 802              fontConfig.initReorderMap();
 803         }
 804         HashMap<String, Object> reorderMap = fontConfig.reorderMap;
 805 
 806         /* Find the most specific mapping */
 807         String language = startupLocale.getLanguage();
 808         String country = startupLocale.getCountry();
 809         Object val = reorderMap.get(encoding + "." + language + "." + country);
 810         if (val == null) {
 811             val = reorderMap.get(encoding + "." + language);
 812         }
 813         if (val == null) {
 814             val = reorderMap.get(encoding);
 815         }
 816         return val;
 817     }
 818 
 819     /* This method reorders the sequence such that the matches for the
 820      * file encoding are moved ahead of other elements.
 821      * If an encoding uses more than one font, they are all moved up.
 822      */
 823      private void reorderSequenceForLocale(String[] seq) {
 824         Object val =  getReorderSequence();
 825         if (val instanceof String) {
 826             for (int i=0; i< seq.length; i++) {
 827                 if (seq[i].equals(val)) {
 828                     shuffle(seq, i, 0);
 829                     return;
 830                 }
 831             }
 832         } else if (val instanceof String[]) {
 833             String[] fontLangs = (String[])val;
 834             for (int l=0; l<fontLangs.length;l++) {
 835                 for (int i=0; i<seq.length;i++) {
 836                     if (seq[i].equals(fontLangs[l])) {
 837                         shuffle(seq, i, l);
 838                     }
 839                 }
 840             }
 841         }
 842     }
 843 
 844     private static Vector<String> splitSequence(String sequence) {
 845         //String.split would be more convenient, but incurs big performance penalty
 846         Vector<String> parts = new Vector<>();
 847         int start = 0;
 848         int end;
 849         while ((end = sequence.indexOf(',', start)) >= 0) {
 850             parts.add(sequence.substring(start, end));
 851             start = end + 1;
 852         }
 853         if (sequence.length() > start) {
 854             parts.add(sequence.substring(start, sequence.length()));
 855         }
 856         return parts;
 857     }
 858 
 859     protected String[] split(String sequence) {
 860         Vector<String> v = splitSequence(sequence);
 861         return v.toArray(new String[0]);
 862     }
 863 
 864     ////////////////////////////////////////////////////////////////////////
 865     // Methods for extracting information from the fontconfig data for AWT//
 866     ////////////////////////////////////////////////////////////////////////
 867     private Hashtable<String, Charset> charsetRegistry = new Hashtable<>(5);
 868 
 869     /**
 870      * Returns FontDescriptors describing the physical fonts used for the
 871      * given logical font name and style. The font name is interpreted
 872      * in a case insensitive way.
 873      * The style argument is interpreted as in java.awt.Font.Font.
 874      */
 875     public FontDescriptor[] getFontDescriptors(String fontName, int style) {
 876         assert isLogicalFontFamilyName(fontName);
 877         fontName = fontName.toLowerCase(Locale.ENGLISH);
 878         int fontIndex = getFontIndex(fontName);
 879         int styleIndex = getStyleIndex(style);
 880         return getFontDescriptors(fontIndex, styleIndex);
 881     }
 882     private FontDescriptor[][][] fontDescriptors =
 883         new FontDescriptor[NUM_FONTS][NUM_STYLES][];
 884 
 885     private FontDescriptor[] getFontDescriptors(int fontIndex, int styleIndex) {
 886         FontDescriptor[] descriptors = fontDescriptors[fontIndex][styleIndex];
 887         if (descriptors == null) {
 888             descriptors = buildFontDescriptors(fontIndex, styleIndex);
 889             fontDescriptors[fontIndex][styleIndex] = descriptors;
 890         }
 891         return descriptors;
 892     }
 893 
 894     protected FontDescriptor[] buildFontDescriptors(int fontIndex, int styleIndex) {
 895         String fontName = fontNames[fontIndex];
 896         String styleName = styleNames[styleIndex];
 897 
 898         short[] scriptIDs = getCoreScripts(fontIndex);
 899         short[] nameIDs = compFontNameIDs[fontIndex][styleIndex];
 900         String[] sequence = new String[scriptIDs.length];
 901         String[] names = new String[scriptIDs.length];
 902         for (int i = 0; i < sequence.length; i++) {
 903             names[i] = getComponentFontName(nameIDs[i]);
 904             sequence[i] = getScriptName(scriptIDs[i]);
 905             if (alphabeticSuffix != null && "alphabetic".equals(sequence[i])) {
 906                 sequence[i] = sequence[i] + "/" + alphabeticSuffix;
 907             }
 908         }
 909         int[][] fontExclusionRanges = compExclusions[fontIndex];
 910 
 911         FontDescriptor[] descriptors = new FontDescriptor[names.length];
 912 
 913         for (int i = 0; i < names.length; i++) {
 914             String awtFontName;
 915             String encoding;
 916 
 917             awtFontName = makeAWTFontName(names[i], sequence[i]);
 918 
 919             // look up character encoding
 920             encoding = getEncoding(names[i], sequence[i]);
 921             if (encoding == null) {
 922                 encoding = "default";
 923             }
 924             CharsetEncoder enc
 925                     = getFontCharsetEncoder(encoding.trim(), awtFontName);
 926 
 927             // we already have the exclusion ranges
 928             int[] exclusionRanges = fontExclusionRanges[i];
 929 
 930             // create descriptor
 931             descriptors[i] = new FontDescriptor(awtFontName, enc, exclusionRanges);
 932         }
 933         return descriptors;
 934     }
 935 
 936     /**
 937      * Returns the AWT font name for the given platform font name and
 938      * character subset.
 939      */
 940     protected String makeAWTFontName(String platformFontName,
 941             String characterSubsetName) {
 942         return platformFontName;
 943     }
 944 
 945     /**
 946      * Returns the java.io name of the platform character encoding for the
 947      * given AWT font name and character subset. May return "default"
 948      * to indicate that getDefaultFontCharset should be called to obtain
 949      * a charset encoder.
 950      */
 951     protected abstract String getEncoding(String awtFontName,
 952             String characterSubsetName);
 953 
 954     private CharsetEncoder getFontCharsetEncoder(final String charsetName,
 955             String fontName) {
 956 
 957         Charset fc = null;
 958         if (charsetName.equals("default")) {
 959             fc = charsetRegistry.get(fontName);
 960         } else {
 961             fc = charsetRegistry.get(charsetName);
 962         }
 963         if (fc != null) {
 964             return fc.newEncoder();
 965         }
 966 
 967         if (!charsetName.startsWith("sun.awt.") && !charsetName.equals("default")) {
 968             fc = Charset.forName(charsetName);
 969         } else {
 970             Class<?> fcc = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
 971                     public Class<?> run() {
 972                         try {
 973                             return Class.forName(charsetName, true,
 974                                                  ClassLoader.getSystemClassLoader());
 975                         } catch (ClassNotFoundException e) {
 976                         }
 977                         return null;
 978                     }
 979                 });
 980 
 981             if (fcc != null) {
 982                 try {
 983                     fc = (Charset) fcc.getDeclaredConstructor().newInstance();
 984                 } catch (Exception e) {
 985                 }
 986             }
 987         }
 988         if (fc == null) {
 989             fc = getDefaultFontCharset(fontName);
 990         }
 991 
 992         if (charsetName.equals("default")){
 993             charsetRegistry.put(fontName, fc);
 994         } else {
 995             charsetRegistry.put(charsetName, fc);
 996         }
 997         return fc.newEncoder();
 998     }
 999 
1000     protected abstract Charset getDefaultFontCharset(
1001             String fontName);
1002 
1003     /* This retrieves the platform font directories (path) calculated
1004      * by setAWTFontPathSequence(String[]). The default implementation
1005      * returns null, its expected that X11 platforms may return
1006      * non-null.
1007      */
1008     public HashSet<String> getAWTFontPathSet() {
1009         return null;
1010     }
1011 
1012     ////////////////////////////////////////////////////////////////////////
1013     // methods for extracting information from the fontconfig data for 2D //
1014     ////////////////////////////////////////////////////////////////////////
1015 
1016     /**
1017      * Returns an array of composite font descriptors for all logical font
1018      * faces.
1019      */
1020     public CompositeFontDescriptor[] get2DCompositeFontInfo() {
1021         CompositeFontDescriptor[] result =
1022                 new CompositeFontDescriptor[NUM_FONTS * NUM_STYLES];
1023         String defaultFontFile = fontManager.getDefaultFontFile();
1024         String defaultFontFaceName = fontManager.getDefaultFontFaceName();
1025 
1026         for (int fontIndex = 0; fontIndex < NUM_FONTS; fontIndex++) {
1027             String fontName = publicFontNames[fontIndex];
1028 
1029             // determine exclusion ranges for font
1030             // AWT uses separate exclusion range array per component font.
1031             // 2D packs all range boundaries into one array.
1032             // Both use separate entries for lower and upper boundary.
1033             int[][] exclusions = compExclusions[fontIndex];
1034             int numExclusionRanges = 0;
1035             for (int i = 0; i < exclusions.length; i++) {
1036                 numExclusionRanges += exclusions[i].length;
1037             }
1038             int[] exclusionRanges = new int[numExclusionRanges];
1039             int[] exclusionRangeLimits = new int[exclusions.length];
1040             int exclusionRangeIndex = 0;
1041             int exclusionRangeLimitIndex = 0;
1042             for (int i = 0; i < exclusions.length; i++) {
1043                 int[] componentRanges = exclusions[i];
1044                 for (int j = 0; j < componentRanges.length; ) {
1045                     int value = componentRanges[j];
1046                     exclusionRanges[exclusionRangeIndex++] = componentRanges[j++];
1047                     exclusionRanges[exclusionRangeIndex++] = componentRanges[j++];
1048                 }
1049                 exclusionRangeLimits[i] = exclusionRangeIndex;
1050             }
1051             // other info is per style
1052             for (int styleIndex = 0; styleIndex < NUM_STYLES; styleIndex++) {
1053                 int maxComponentFontCount = compFontNameIDs[fontIndex][styleIndex].length;
1054                 // fall back fonts listed in the lib/fonts/fallback directory
1055                 if (installedFallbackFontFiles != null) {
1056                     maxComponentFontCount += installedFallbackFontFiles.length;
1057                 }
1058                 String faceName = fontName + "." + styleNames[styleIndex];
1059 
1060                 // determine face names and file names of component fonts
1061                 String[] componentFaceNames = new String[maxComponentFontCount];
1062                 String[] componentFileNames = new String[maxComponentFontCount];
1063 
1064                 int index;
1065                 for (index = 0; index < compFontNameIDs[fontIndex][styleIndex].length; index++) {
1066                     short fontNameID = compFontNameIDs[fontIndex][styleIndex][index];
1067                     short fileNameID = getComponentFileID(fontNameID);
1068                     componentFaceNames[index] = getFaceNameFromComponentFontName(getComponentFontName(fontNameID));
1069                     componentFileNames[index] = mapFileName(getComponentFileName(fileNameID));
1070                     if (componentFileNames[index] == null ||
1071                         needToSearchForFile(componentFileNames[index])) {
1072                         componentFileNames[index] = getFileNameFromComponentFontName(getComponentFontName(fontNameID));
1073                     }
1074                     /*
1075                     System.out.println(publicFontNames[fontIndex] + "." + styleNames[styleIndex] + "."
1076                         + getString(table_scriptIDs[coreScripts[index]]) + "=" + componentFileNames[index]);
1077                     */
1078                 }
1079 
1080                 if (installedFallbackFontFiles != null) {
1081                     for (int ifb=0; ifb<installedFallbackFontFiles.length; ifb++) {
1082                         componentFaceNames[index] = null;
1083                         componentFileNames[index] = installedFallbackFontFiles[ifb];
1084                         index++;
1085                     }
1086                 }
1087 
1088                 if (index < maxComponentFontCount) {
1089                     String[] newComponentFaceNames = new String[index];
1090                     System.arraycopy(componentFaceNames, 0, newComponentFaceNames, 0, index);
1091                     componentFaceNames = newComponentFaceNames;
1092                     String[] newComponentFileNames = new String[index];
1093                     System.arraycopy(componentFileNames, 0, newComponentFileNames, 0, index);
1094                     componentFileNames = newComponentFileNames;
1095                 }
1096                 // exclusion range limit array length must match component face name
1097                 // array length - native code relies on this
1098 
1099                 int[] clippedExclusionRangeLimits = exclusionRangeLimits;
1100                 if (index != clippedExclusionRangeLimits.length) {
1101                     int len = exclusionRangeLimits.length;
1102                     clippedExclusionRangeLimits = new int[index];
1103                     System.arraycopy(exclusionRangeLimits, 0, clippedExclusionRangeLimits, 0, len);
1104                     //padding for various fallback fonts
1105                     for (int i = len; i < index; i++) {
1106                         clippedExclusionRangeLimits[i] = exclusionRanges.length;
1107                     }
1108                 }
1109                 /*
1110                 System.out.println(faceName + ":");
1111                 for (int i = 0; i < componentFileNames.length; i++) {
1112                     System.out.println("    " + componentFaceNames[i]
1113                          + "  -> " + componentFileNames[i]);
1114                 }
1115                 */
1116                 result[fontIndex * NUM_STYLES + styleIndex]
1117                         = new CompositeFontDescriptor(
1118                             faceName,
1119                             compCoreNum[fontIndex],
1120                             componentFaceNames,
1121                             componentFileNames,
1122                             exclusionRanges,
1123                             clippedExclusionRangeLimits);
1124             }
1125         }
1126         return result;
1127     }
1128 
1129     protected abstract String getFaceNameFromComponentFontName(String componentFontName);
1130     protected abstract String getFileNameFromComponentFontName(String componentFontName);
1131 
1132     /*
1133     public class 2dFont {
1134         public String platformName;
1135         public String fontfileName;
1136     }
1137     private 2dFont [] componentFonts = null;
1138     */
1139 
1140     /* Used on Linux to test if a file referenced in a font configuration
1141      * file exists in the location that is expected. If it does, no need
1142      * to search for it. If it doesn't then unless its a fallback font,
1143      * return that expensive code should be invoked to search for the font.
1144      */
1145     HashMap<String, Boolean> existsMap;
1146     public boolean needToSearchForFile(String fileName) {
1147         if (!FontUtilities.isLinux) {
1148             return false;
1149         } else if (existsMap == null) {
1150            existsMap = new HashMap<String, Boolean>();
1151         }
1152         Boolean exists = existsMap.get(fileName);
1153         if (exists == null) {
1154             /* call getNumberCoreFonts() to ensure these are initialised, and
1155              * if this file isn't for a core component, ie, is a for a fallback
1156              * font which very typically isn't available, then can't afford
1157              * to take the start-up penalty to search for it.
1158              */
1159             getNumberCoreFonts();
1160             if (!coreFontFileNames.contains(fileName)) {
1161                 exists = Boolean.TRUE;
1162             } else {
1163                 exists = Boolean.valueOf((new File(fileName)).exists());
1164                 existsMap.put(fileName, exists);
1165                 if (FontUtilities.debugFonts() &&
1166                     exists == Boolean.FALSE) {
1167                     logger.warning("Couldn't locate font file " + fileName);
1168                 }
1169             }
1170         }
1171         return exists == Boolean.FALSE;
1172     }
1173 
1174     private int numCoreFonts = -1;
1175     private String[] componentFonts = null;
1176     HashMap <String, String> filenamesMap = new HashMap<String, String>();
1177     HashSet <String> coreFontFileNames = new HashSet<String>();
1178 
1179     /* Return the number of core fonts. Note this isn't thread safe but
1180      * a calling thread can call this and getPlatformFontNames() in either
1181      * order.
1182      */
1183     public int getNumberCoreFonts() {
1184         if (numCoreFonts == -1) {
1185             numCoreFonts = coreFontNameIDs.size();
1186             Short[] emptyShortArray = new Short[0];
1187             Short[] core = coreFontNameIDs.toArray(emptyShortArray);
1188             Short[] fallback = fallbackFontNameIDs.toArray(emptyShortArray);
1189 
1190             int numFallbackFonts = 0;
1191             int i;
1192             for (i = 0; i < fallback.length; i++) {
1193                 if (coreFontNameIDs.contains(fallback[i])) {
1194                     fallback[i] = null;
1195                     continue;
1196                 }
1197                 numFallbackFonts++;
1198             }
1199             componentFonts = new String[numCoreFonts + numFallbackFonts];
1200             String filename = null;
1201             for (i = 0; i < core.length; i++) {
1202                 short fontid = core[i];
1203                 short fileid = getComponentFileID(fontid);
1204                 componentFonts[i] = getComponentFontName(fontid);
1205                 String compFileName = getComponentFileName(fileid);
1206                 if (compFileName != null) {
1207                     coreFontFileNames.add(compFileName);
1208                 }
1209                 filenamesMap.put(componentFonts[i], mapFileName(compFileName));
1210             }
1211             for (int j = 0; j < fallback.length; j++) {
1212                 if (fallback[j] != null) {
1213                     short fontid = fallback[j];
1214                     short fileid = getComponentFileID(fontid);
1215                     componentFonts[i] = getComponentFontName(fontid);
1216                     filenamesMap.put(componentFonts[i],
1217                                      mapFileName(getComponentFileName(fileid)));
1218                     i++;
1219                 }
1220             }
1221         }
1222         return numCoreFonts;
1223     }
1224 
1225     /* Return all platform font names used by this font configuration.
1226      * The first getNumberCoreFonts() entries are guaranteed to be the
1227      * core fonts - ie no fall back only fonts.
1228      */
1229     public String[] getPlatformFontNames() {
1230         if (numCoreFonts == -1) {
1231             getNumberCoreFonts();
1232         }
1233         return componentFonts;
1234     }
1235 
1236     /**
1237      * Returns a file name for the physical font represented by this platform font name,
1238      * if the font configuration has such information available, or null if the
1239      * information is unavailable. The file name returned is just a hint; a null return
1240      * value doesn't necessarily mean that the font is unavailable, nor does a non-null
1241      * return value guarantee that the file exists and contains the physical font.
1242      * The file name can be an absolute or a relative path name.
1243      */
1244     public String getFileNameFromPlatformName(String platformName) {
1245         // get2DCompositeFontInfo
1246         //     ->  getFileNameFromComponentfontName()  (W/M)
1247         //       ->   getFileNameFromPlatformName()
1248         // it's a waste of time on Win32, but I have to give X11 a chance to
1249         // call getFileNameFromXLFD()
1250         return filenamesMap.get(platformName);
1251     }
1252 
1253     /**
1254      * Returns a configuration specific path to be appended to the font
1255      * search path.
1256      */
1257     public String getExtraFontPath() {
1258         return getString(head[INDEX_appendedfontpath]);
1259     }
1260 
1261     public String getVersion() {
1262         return getString(head[INDEX_version]);
1263     }
1264 
1265     /* subclass support */
1266     protected static FontConfiguration getFontConfiguration() {
1267         return fontConfig;
1268     }
1269 
1270     protected void setFontConfiguration() {
1271         fontConfig = this;      /* static initialization */
1272     }
1273 
1274     //////////////////////////////////////////////////////////////////////
1275     // FontConfig data tables and the index constants in binary file    //
1276     //////////////////////////////////////////////////////////////////////
1277     /* The binary font configuration file begins with a short[] "head", which
1278      * contains the offsets to the starts of the individual data table which
1279      * immediately follow. The current implementation includes the tables shown
1280      * below.
1281      *
1282      * (00) table_scriptIDs    :stringIDs of all defined CharacterSubsetNames
1283      * (01) table_scriptFonts  :scriptID x fontIndex x styleIndex->
1284      *                          PlatformFontNameID mapping. Each scriptID might
1285      *                          have 1 or 20 entries depends on if it is defined
1286      *                          via a "allfonts.CharacterSubsetname" or a list of
1287      *                          "LogicalFontName.StyleName.CharacterSubsetName"
1288      *                          entries, positive entry means it's a "allfonts"
1289      *                          entry, a negative value means this is a offset to
1290      *                          a NUM_FONTS x NUM_STYLES subtable.
1291      * (02) table_elcIDs       :stringIDs of all defined ELC names, string
1292      *                          "NULL.NULL.NULL" is used for "default"
1293      * (03) table_sequences    :elcID x logicalFont -> scriptIDs table defined
1294      *                          by "sequence.allfonts/LogicalFontName.ELC" in
1295      *                          font configuration file, each "elcID" has
1296      *                          NUM_FONTS (5) entries in this table.
1297      * (04) table_fontfileNameIDs
1298      *                         :stringIDs of all defined font file names
1299      * (05) table_componentFontNameIDs
1300      *                         :stringIDs of all defined PlatformFontNames
1301      * (06) table_filenames    :platformFontNamesID->fontfileNameID mapping
1302      *                          table, the index is the platformFontNamesID.
1303      * (07) table_awtfontpaths :CharacterSubsetNames->awtfontpaths mapping table,
1304      *                          the index is the CharacterSubsetName's stringID
1305      *                          and content is the stringID of awtfontpath.
1306      * (08) table_exclusions   :scriptID -> exclusionRanges mapping table,
1307      *                          the index is the scriptID and the content is
1308                                 a id of an exclusionRanges int[].
1309      * (09) table_proportionals:list of pairs of PlatformFontNameIDs, stores
1310      *                          the replacement info defined by "proportional"
1311      *                          keyword.
1312      * (10) table_scriptFontsMotif
1313      *                         :same as (01) except this table stores the
1314      *                          info defined with ".motif" keyword
1315      * (11) table_alphabeticSuffix
1316      *                         :elcID -> stringID of alphabetic/XXXX entries
1317      * (12) table_stringIDs    :The index of this table is the string ID, the
1318      *                          content is the "start index" of this string in
1319      *                          stringTable, use the start index of next entry
1320      *                          as the "end index".
1321      * (13) table_stringTable  :The real storage of all character strings defined
1322      *                          /used this font configuration, need a pair of
1323      *                          "start" and "end" indices to access.
1324      * (14) reserved
1325      * (15) table_fallbackScripts
1326      *                         :stringIDs of fallback CharacterSubsetnames, stored
1327      *                          in the order of they are defined in sequence.fallback.
1328      * (16) table_appendedfontpath
1329      *                         :stringtID of the "appendedfontpath" defined.
1330      * (17) table_version   :stringID of the version number of this fontconfig file.
1331      */
1332     private static final int HEAD_LENGTH = 20;
1333     private static final int INDEX_scriptIDs = 0;
1334     private static final int INDEX_scriptFonts = 1;
1335     private static final int INDEX_elcIDs = 2;
1336     private static final int INDEX_sequences = 3;
1337     private static final int INDEX_fontfileNameIDs = 4;
1338     private static final int INDEX_componentFontNameIDs = 5;
1339     private static final int INDEX_filenames = 6;
1340     private static final int INDEX_awtfontpaths = 7;
1341     private static final int INDEX_exclusions = 8;
1342     private static final int INDEX_proportionals = 9;
1343     private static final int INDEX_scriptFontsMotif = 10;
1344     private static final int INDEX_alphabeticSuffix = 11;
1345     private static final int INDEX_stringIDs = 12;
1346     private static final int INDEX_stringTable = 13;
1347     private static final int INDEX_TABLEEND = 14;
1348     private static final int INDEX_fallbackScripts = 15;
1349     private static final int INDEX_appendedfontpath = 16;
1350     private static final int INDEX_version = 17;
1351 
1352     private static short[] head;
1353     private static short[] table_scriptIDs;
1354     private static short[] table_scriptFonts;
1355     private static short[] table_elcIDs;
1356     private static short[] table_sequences;
1357     private static short[] table_fontfileNameIDs;
1358     private static short[] table_componentFontNameIDs;
1359     private static short[] table_filenames;
1360     protected static short[] table_awtfontpaths;
1361     private static short[] table_exclusions;
1362     private static short[] table_proportionals;
1363     private static short[] table_scriptFontsMotif;
1364     private static short[] table_alphabeticSuffix;
1365     private static short[] table_stringIDs;
1366     private static char[]  table_stringTable;
1367 
1368     /**
1369      * Checks consistencies of complied fontconfig data. This method
1370      * is called only at the build-time from
1371      * build.tools.compilefontconfig.CompileFontConfig.
1372      */
1373     private static void sanityCheck() {
1374         int errors = 0;
1375 
1376         //This method will only be called during build time, do we
1377         //need do PrivilegedAction?
1378         String osName = java.security.AccessController.doPrivileged(
1379                             new java.security.PrivilegedAction<String>() {
1380             public String run() {
1381                 return System.getProperty("os.name");
1382             }
1383         });
1384 
1385         //componentFontNameID starts from "1"
1386         for (int ii = 1; ii < table_filenames.length; ii++) {
1387             if (table_filenames[ii] == -1) {
1388                 // The corresponding finename entry for a component
1389                 // font name is mandatory on Windows, but it's
1390                 // optional on Solaris and Linux.
1391                 if (osName.contains("Windows")) {
1392                     System.err.println("\n Error: <filename."
1393                                        + getString(table_componentFontNameIDs[ii])
1394                                        + "> entry is missing!!!");
1395                     errors++;
1396                 } else {
1397                     if (verbose && !isEmpty(table_filenames)) {
1398                         System.err.println("\n Note: 'filename' entry is undefined for \""
1399                                            + getString(table_componentFontNameIDs[ii])
1400                                            + "\"");
1401                     }
1402                 }
1403             }
1404         }
1405         for (int ii = 0; ii < table_scriptIDs.length; ii++) {
1406             short fid = table_scriptFonts[ii];
1407             if (fid == 0) {
1408                 System.out.println("\n Error: <allfonts."
1409                                    + getString(table_scriptIDs[ii])
1410                                    + "> entry is missing!!!");
1411                 errors++;
1412                 continue;
1413             } else if (fid < 0) {
1414                 fid = (short)-fid;
1415                 for (int iii = 0; iii < NUM_FONTS; iii++) {
1416                     for (int iij = 0; iij < NUM_STYLES; iij++) {
1417                         int jj = iii * NUM_STYLES + iij;
1418                         short ffid = table_scriptFonts[fid + jj];
1419                         if (ffid == 0) {
1420                             System.err.println("\n Error: <"
1421                                            + getFontName(iii) + "."
1422                                            + getStyleName(iij) + "."
1423                                            + getString(table_scriptIDs[ii])
1424                                            + "> entry is missing!!!");
1425                             errors++;
1426                         }
1427                     }
1428                 }
1429             }
1430         }
1431         if (errors != 0) {
1432             System.err.println("!!THERE ARE " + errors + " ERROR(S) IN "
1433                                + "THE FONTCONFIG FILE, PLEASE CHECK ITS CONTENT!!\n");
1434             System.exit(1);
1435         }
1436     }
1437 
1438     private static boolean isEmpty(short[] a) {
1439         for (short s : a) {
1440             if (s != -1) {
1441                 return false;
1442             }
1443         }
1444         return true;
1445     }
1446 
1447     //dump the fontconfig data tables
1448     private static void dump() {
1449         System.out.println("\n----Head Table------------");
1450         for (int ii = 0; ii < HEAD_LENGTH; ii++) {
1451             System.out.println("  " + ii + " : " + head[ii]);
1452         }
1453         System.out.println("\n----scriptIDs-------------");
1454         printTable(table_scriptIDs, 0);
1455         System.out.println("\n----scriptFonts----------------");
1456         for (int ii = 0; ii < table_scriptIDs.length; ii++) {
1457             short fid = table_scriptFonts[ii];
1458             if (fid >= 0) {
1459                 System.out.println("  allfonts."
1460                                    + getString(table_scriptIDs[ii])
1461                                    + "="
1462                                    + getString(table_componentFontNameIDs[fid]));
1463             }
1464         }
1465         for (int ii = 0; ii < table_scriptIDs.length; ii++) {
1466             short fid = table_scriptFonts[ii];
1467             if (fid < 0) {
1468                 fid = (short)-fid;
1469                 for (int iii = 0; iii < NUM_FONTS; iii++) {
1470                     for (int iij = 0; iij < NUM_STYLES; iij++) {
1471                         int jj = iii * NUM_STYLES + iij;
1472                         short ffid = table_scriptFonts[fid + jj];
1473                         System.out.println("  "
1474                                            + getFontName(iii) + "."
1475                                            + getStyleName(iij) + "."
1476                                            + getString(table_scriptIDs[ii])
1477                                            + "="
1478                                            + getString(table_componentFontNameIDs[ffid]));
1479                     }
1480                 }
1481 
1482             }
1483         }
1484         System.out.println("\n----elcIDs----------------");
1485         printTable(table_elcIDs, 0);
1486         System.out.println("\n----sequences-------------");
1487         for (int ii = 0; ii< table_elcIDs.length; ii++) {
1488             System.out.println("  " + ii + "/" + getString(table_elcIDs[ii]));
1489             short[] ss = getShortArray(table_sequences[ii * NUM_FONTS + 0]);
1490             for (int jj = 0; jj < ss.length; jj++) {
1491                 System.out.println("     " + getString(table_scriptIDs[ss[jj]]));
1492             }
1493         }
1494         System.out.println("\n----fontfileNameIDs-------");
1495         printTable(table_fontfileNameIDs, 0);
1496 
1497         System.out.println("\n----componentFontNameIDs--");
1498         printTable(table_componentFontNameIDs, 1);
1499         System.out.println("\n----filenames-------------");
1500         for (int ii = 0; ii < table_filenames.length; ii++) {
1501             if (table_filenames[ii] == -1) {
1502                 System.out.println("  " + ii + " : null");
1503             } else {
1504                 System.out.println("  " + ii + " : "
1505                    + getString(table_fontfileNameIDs[table_filenames[ii]]));
1506             }
1507         }
1508         System.out.println("\n----awtfontpaths---------");
1509         for (int ii = 0; ii < table_awtfontpaths.length; ii++) {
1510             System.out.println("  " + getString(table_scriptIDs[ii])
1511                                + " : "
1512                                + getString(table_awtfontpaths[ii]));
1513         }
1514         System.out.println("\n----proportionals--------");
1515         for (int ii = 0; ii < table_proportionals.length; ii++) {
1516             System.out.println("  "
1517                    + getString(table_componentFontNameIDs[table_proportionals[ii++]])
1518                    + " -> "
1519                    + getString(table_componentFontNameIDs[table_proportionals[ii]]));
1520         }
1521         int i = 0;
1522         System.out.println("\n----alphabeticSuffix----");
1523         while (i < table_alphabeticSuffix.length) {
1524           System.out.println("    " + getString(table_elcIDs[table_alphabeticSuffix[i++]])
1525                              + " -> " + getString(table_alphabeticSuffix[i++]));
1526         }
1527         System.out.println("\n----String Table---------");
1528         System.out.println("    stringID:    Num =" + table_stringIDs.length);
1529         System.out.println("    stringTable: Size=" + table_stringTable.length * 2);
1530 
1531         System.out.println("\n----fallbackScriptIDs---");
1532         short[] fbsIDs = getShortArray(head[INDEX_fallbackScripts]);
1533         for (int ii = 0; ii < fbsIDs.length; ii++) {
1534           System.out.println("  " + getString(table_scriptIDs[fbsIDs[ii]]));
1535         }
1536         System.out.println("\n----appendedfontpath-----");
1537         System.out.println("  " + getString(head[INDEX_appendedfontpath]));
1538         System.out.println("\n----Version--------------");
1539         System.out.println("  " + getString(head[INDEX_version]));
1540     }
1541 
1542 
1543     //////////////////////////////////////////////////////////////////////
1544     // Data table access methods                                        //
1545     //////////////////////////////////////////////////////////////////////
1546 
1547     /* Return the fontID of the platformFontName defined in this font config
1548      * by "LogicalFontName.StyleName.CharacterSubsetName" entry or
1549      * "allfonts.CharacterSubsetName" entry in properties format fc file.
1550      */
1551     protected static short getComponentFontID(short scriptID, int fontIndex, int styleIndex) {
1552         short fid = table_scriptFonts[scriptID];
1553         //System.out.println("fid=" + fid + "/ scriptID=" + scriptID + ", fi=" + fontIndex + ", si=" + styleIndex);
1554         if (fid >= 0) {
1555             //"allfonts"
1556             return fid;
1557         } else {
1558             return table_scriptFonts[-fid + fontIndex * NUM_STYLES + styleIndex];
1559         }
1560     }
1561 
1562     /* Same as getCompoentFontID() except this method returns the fontID define by
1563      * "xxxx.motif" entry.
1564      */
1565     protected static short getComponentFontIDMotif(short scriptID, int fontIndex, int styleIndex) {
1566         if (table_scriptFontsMotif.length == 0) {
1567             return 0;
1568         }
1569         short fid = table_scriptFontsMotif[scriptID];
1570         if (fid >= 0) {
1571             //"allfonts" > 0 or "not defined" == 0
1572             return fid;
1573         } else {
1574             return table_scriptFontsMotif[-fid + fontIndex * NUM_STYLES + styleIndex];
1575         }
1576     }
1577 
1578     private static int[] getExclusionRanges(short scriptID) {
1579         short exID = table_exclusions[scriptID];
1580         if (exID == 0) {
1581             return EMPTY_INT_ARRAY;
1582         } else {
1583             char[] exChar = getString(exID).toCharArray();
1584             int[] exInt = new int[exChar.length / 2];
1585             int i = 0;
1586             for (int j = 0; j < exInt.length; j++) {
1587                 exInt[j] = (exChar[i++] << 16) + (exChar[i++] & 0xffff);
1588             }
1589             return exInt;
1590         }
1591     }
1592 
1593     private static boolean contains(short[] IDs, short id, int limit) {
1594         for (int i = 0; i < limit; i++) {
1595             if (IDs[i] == id) {
1596                 return true;
1597             }
1598         }
1599         return false;
1600     }
1601 
1602     /* Return the PlatformFontName from its fontID*/
1603     protected static String getComponentFontName(short id) {
1604         if (id < 0) {
1605             return null;
1606         }
1607         return getString(table_componentFontNameIDs[id]);
1608     }
1609 
1610     private static String getComponentFileName(short id) {
1611         if (id < 0) {
1612             return null;
1613         }
1614         return getString(table_fontfileNameIDs[id]);
1615     }
1616 
1617     //componentFontID -> componentFileID
1618     private static short getComponentFileID(short nameID) {
1619         return table_filenames[nameID];
1620     }
1621 
1622     private static String getScriptName(short scriptID) {
1623         return getString(table_scriptIDs[scriptID]);
1624     }
1625 
1626    private HashMap<String, Short> reorderScripts;
1627    protected short[] getCoreScripts(int fontIndex) {
1628         short elc = getInitELC();
1629         /*
1630           System.out.println("getCoreScripts: elc=" + elc + ", fontIndex=" + fontIndex);
1631           short[] ss = getShortArray(table_sequences[elc * NUM_FONTS + fontIndex]);
1632           for (int i = 0; i < ss.length; i++) {
1633               System.out.println("     " + getString((short)table_scriptIDs[ss[i]]));
1634           }
1635           */
1636         short[] scripts = getShortArray(table_sequences[elc * NUM_FONTS + fontIndex]);
1637         if (preferLocaleFonts) {
1638             if (reorderScripts == null) {
1639                 reorderScripts = new HashMap<String, Short>();
1640             }
1641             String[] ss = new String[scripts.length];
1642             for (int i = 0; i < ss.length; i++) {
1643                 ss[i] = getScriptName(scripts[i]);
1644                 reorderScripts.put(ss[i], scripts[i]);
1645             }
1646             reorderSequenceForLocale(ss);
1647             for (int i = 0; i < ss.length; i++) {
1648                 scripts[i] = reorderScripts.get(ss[i]);
1649             }
1650         }
1651          return scripts;
1652     }
1653 
1654     private static short[] getFallbackScripts() {
1655         return getShortArray(head[INDEX_fallbackScripts]);
1656     }
1657 
1658     private static void printTable(short[] list, int start) {
1659         for (int i = start; i < list.length; i++) {
1660             System.out.println("  " + i + " : " + getString(list[i]));
1661         }
1662     }
1663 
1664     private static short[] readShortTable(DataInputStream in, int len )
1665         throws IOException {
1666         if (len == 0) {
1667             return EMPTY_SHORT_ARRAY;
1668         }
1669         short[] data = new short[len];
1670         byte[] bb = new byte[len * 2];
1671         in.read(bb);
1672         int i = 0,j = 0;
1673         while (i < len) {
1674             data[i++] = (short)(bb[j++] << 8 | (bb[j++] & 0xff));
1675         }
1676         return data;
1677     }
1678 
1679     private static void writeShortTable(DataOutputStream out, short[] data)
1680         throws IOException {
1681         for (short val : data) {
1682             out.writeShort(val);
1683         }
1684     }
1685 
1686     private static short[] toList(HashMap<String, Short> map) {
1687         short[] list = new short[map.size()];
1688         Arrays.fill(list, (short) -1);
1689         for (Entry<String, Short> entry : map.entrySet()) {
1690             list[entry.getValue()] = getStringID(entry.getKey());
1691         }
1692         return list;
1693     }
1694 
1695     //runtime cache
1696     private static String[] stringCache;
1697     protected static String getString(short stringID) {
1698         if (stringID == 0)
1699             return null;
1700         /*
1701         if (loadingProperties) {
1702             return stringTable.substring(stringIDs[stringID],
1703                                          stringIDs[stringID+1]);
1704         }
1705         */
1706         //sync if we want it to be MT-enabled
1707         if (stringCache[stringID] == null){
1708             stringCache[stringID] =
1709               new String (table_stringTable,
1710                           table_stringIDs[stringID],
1711                           table_stringIDs[stringID+1] - table_stringIDs[stringID]);
1712         }
1713         return stringCache[stringID];
1714     }
1715 
1716     private static short[] getShortArray(short shortArrayID) {
1717         String s = getString(shortArrayID);
1718         char[] cc = s.toCharArray();
1719         short[] ss = new short[cc.length];
1720         for (int i = 0; i < cc.length; i++) {
1721             ss[i] = (short)(cc[i] & 0xffff);
1722         }
1723         return ss;
1724     }
1725 
1726     private static short getStringID(String s) {
1727         if (s == null) {
1728             return (short)0;
1729         }
1730         short pos0 = (short)stringTable.length();
1731         stringTable.append(s);
1732         short pos1 = (short)stringTable.length();
1733 
1734         stringIDs[stringIDNum] = pos0;
1735         stringIDs[stringIDNum + 1] = pos1;
1736         stringIDNum++;
1737         if (stringIDNum + 1 >= stringIDs.length) {
1738             short[] tmp = new short[stringIDNum + 1000];
1739             System.arraycopy(stringIDs, 0, tmp, 0, stringIDNum);
1740             stringIDs = tmp;
1741         }
1742         return (short)(stringIDNum - 1);
1743     }
1744 
1745     private static short getShortArrayID(short[] sa) {
1746         char[] cc = new char[sa.length];
1747         for (int i = 0; i < sa.length; i ++) {
1748             cc[i] = (char)sa[i];
1749         }
1750         String s = new String(cc);
1751         return getStringID(s);
1752     }
1753 
1754     //utility "empty" objects
1755     private static final int[] EMPTY_INT_ARRAY = new int[0];
1756     private static final String[] EMPTY_STRING_ARRAY = new String[0];
1757     private static final short[] EMPTY_SHORT_ARRAY = new short[0];
1758     private static final String UNDEFINED_COMPONENT_FONT = "unknown";
1759 
1760     //////////////////////////////////////////////////////////////////////////
1761     //Convert the FontConfig data in Properties file to binary data tables  //
1762     //////////////////////////////////////////////////////////////////////////
1763     static class PropertiesHandler {
1764         public void load(InputStream in) throws IOException {
1765             initLogicalNameStyle();
1766             initHashMaps();
1767             FontProperties fp = new FontProperties();
1768             fp.load(in);
1769             initBinaryTable();
1770         }
1771 
1772         private void initBinaryTable() {
1773             //(0)
1774             head = new short[HEAD_LENGTH];
1775             head[INDEX_scriptIDs] = (short)HEAD_LENGTH;
1776 
1777             table_scriptIDs = toList(scriptIDs);
1778             //(1)a: scriptAllfonts scriptID/allfonts -> componentFontNameID
1779             //   b: scriptFonts    scriptID -> componentFontNameID[20]
1780             //if we have a "allfonts.script" def, then we just put
1781             //the "-platformFontID" value in the slot, otherwise the slot
1782             //value is "offset" which "offset" is where 20 entries located
1783             //in the table attached.
1784             head[INDEX_scriptFonts] = (short)(head[INDEX_scriptIDs]  + table_scriptIDs.length);
1785             int len = table_scriptIDs.length + scriptFonts.size() * 20;
1786             table_scriptFonts = new short[len];
1787 
1788             for (Entry<Short, Short> entry : scriptAllfonts.entrySet()) {
1789                 table_scriptFonts[entry.getKey().intValue()] = entry.getValue();
1790             }
1791             int off = table_scriptIDs.length;
1792             for (Entry<Short, Short[]> entry : scriptFonts.entrySet()) {
1793                 table_scriptFonts[entry.getKey().intValue()] = (short)-off;
1794                 Short[] v = entry.getValue();
1795                 for (int i = 0; i < 20; i++) {
1796                     if (v[i] != null) {
1797                         table_scriptFonts[off++] = v[i];
1798                     } else {
1799                         table_scriptFonts[off++] = 0;
1800                     }
1801                 }
1802             }
1803 
1804             //(2)
1805             head[INDEX_elcIDs] = (short)(head[INDEX_scriptFonts]  + table_scriptFonts.length);
1806             table_elcIDs = toList(elcIDs);
1807 
1808             //(3) sequences  elcID -> XXXX[1|5] -> scriptID[]
1809             head[INDEX_sequences] = (short)(head[INDEX_elcIDs]  + table_elcIDs.length);
1810             table_sequences = new short[elcIDs.size() * NUM_FONTS];
1811             for (Entry<Short, short[]> entry : sequences.entrySet()) {
1812                 //table_sequences[entry.getKey().intValue()] = (short)-off;
1813                 int k = entry.getKey().intValue();
1814                 short[] v = entry.getValue();
1815                 /*
1816                   System.out.println("elc=" + k + "/" + getString((short)table_elcIDs[k]));
1817                   short[] ss = getShortArray(v[0]);
1818                   for (int i = 0; i < ss.length; i++) {
1819                   System.out.println("     " + getString((short)table_scriptIDs[ss[i]]));
1820                   }
1821                   */
1822                 if (v.length == 1) {
1823                     //the "allfonts" entries
1824                     for (int i = 0; i < NUM_FONTS; i++) {
1825                         table_sequences[k * NUM_FONTS + i] = v[0];
1826                     }
1827                 } else {
1828                     for (int i = 0; i < NUM_FONTS; i++) {
1829                         table_sequences[k * NUM_FONTS + i] = v[i];
1830                     }
1831                 }
1832             }
1833             //(4)
1834             head[INDEX_fontfileNameIDs] = (short)(head[INDEX_sequences]  + table_sequences.length);
1835             table_fontfileNameIDs = toList(fontfileNameIDs);
1836 
1837             //(5)
1838             head[INDEX_componentFontNameIDs] = (short)(head[INDEX_fontfileNameIDs]  + table_fontfileNameIDs.length);
1839             table_componentFontNameIDs = toList(componentFontNameIDs);
1840 
1841             //(6)componentFontNameID -> filenameID
1842             head[INDEX_filenames] = (short)(head[INDEX_componentFontNameIDs]  + table_componentFontNameIDs.length);
1843             table_filenames = new short[table_componentFontNameIDs.length];
1844             Arrays.fill(table_filenames, (short) -1);
1845 
1846             for (Entry<Short, Short> entry : filenames.entrySet()) {
1847                 table_filenames[entry.getKey()] = entry.getValue();
1848             }
1849 
1850             //(7)scriptID-> awtfontpath
1851             //the paths are stored as scriptID -> stringID in awtfontpahts
1852             head[INDEX_awtfontpaths] = (short)(head[INDEX_filenames]  + table_filenames.length);
1853             table_awtfontpaths = new short[table_scriptIDs.length];
1854             for (Entry<Short, Short> entry : awtfontpaths.entrySet()) {
1855                 table_awtfontpaths[entry.getKey()] = entry.getValue();
1856             }
1857 
1858             //(8)exclusions
1859             head[INDEX_exclusions] = (short)(head[INDEX_awtfontpaths]  + table_awtfontpaths.length);
1860             table_exclusions = new short[scriptIDs.size()];
1861             for (Entry<Short, int[]> entry : exclusions.entrySet()) {
1862                 int[] exI = entry.getValue();
1863                 char[] exC = new char[exI.length * 2];
1864                 int j = 0;
1865                 for (int i = 0; i < exI.length; i++) {
1866                     exC[j++] = (char) (exI[i] >> 16);
1867                     exC[j++] = (char) (exI[i] & 0xffff);
1868                 }
1869                 table_exclusions[entry.getKey()] = getStringID(new String (exC));
1870             }
1871             //(9)proportionals
1872             head[INDEX_proportionals] = (short)(head[INDEX_exclusions]  + table_exclusions.length);
1873             table_proportionals = new short[proportionals.size() * 2];
1874             int j = 0;
1875             for (Entry<Short, Short> entry : proportionals.entrySet()) {
1876                 table_proportionals[j++] = entry.getKey();
1877                 table_proportionals[j++] = entry.getValue();
1878             }
1879 
1880             //(10) see (1) for info, the only difference is "xxx.motif"
1881             head[INDEX_scriptFontsMotif] = (short)(head[INDEX_proportionals] + table_proportionals.length);
1882             if (scriptAllfontsMotif.size() != 0 || scriptFontsMotif.size() != 0) {
1883                 len = table_scriptIDs.length + scriptFontsMotif.size() * 20;
1884                 table_scriptFontsMotif = new short[len];
1885 
1886                 for (Entry<Short, Short> entry : scriptAllfontsMotif.entrySet()) {
1887                     table_scriptFontsMotif[entry.getKey().intValue()] =
1888                       (short)entry.getValue();
1889                 }
1890                 off = table_scriptIDs.length;
1891                 for (Entry<Short, Short[]> entry : scriptFontsMotif.entrySet()) {
1892                     table_scriptFontsMotif[entry.getKey().intValue()] = (short)-off;
1893                     Short[] v = entry.getValue();
1894                     int i = 0;
1895                     while (i < 20) {
1896                         if (v[i] != null) {
1897                             table_scriptFontsMotif[off++] = v[i];
1898                         } else {
1899                             table_scriptFontsMotif[off++] = 0;
1900                         }
1901                         i++;
1902                     }
1903                 }
1904             } else {
1905                 table_scriptFontsMotif = EMPTY_SHORT_ARRAY;
1906             }
1907 
1908             //(11)short[] alphabeticSuffix
1909             head[INDEX_alphabeticSuffix] = (short)(head[INDEX_scriptFontsMotif] + table_scriptFontsMotif.length);
1910             table_alphabeticSuffix = new short[alphabeticSuffix.size() * 2];
1911             j = 0;
1912             for (Entry<Short, Short> entry : alphabeticSuffix.entrySet()) {
1913                 table_alphabeticSuffix[j++] = entry.getKey();
1914                 table_alphabeticSuffix[j++] = entry.getValue();
1915             }
1916 
1917             //(15)short[] fallbackScriptIDs; just put the ID in head
1918             head[INDEX_fallbackScripts] = getShortArrayID(fallbackScriptIDs);
1919 
1920             //(16)appendedfontpath
1921             head[INDEX_appendedfontpath] = getStringID(appendedfontpath);
1922 
1923             //(17)version
1924             head[INDEX_version] = getStringID(version);
1925 
1926             //(12)short[] StringIDs
1927             head[INDEX_stringIDs] = (short)(head[INDEX_alphabeticSuffix] + table_alphabeticSuffix.length);
1928             table_stringIDs = new short[stringIDNum + 1];
1929             System.arraycopy(stringIDs, 0, table_stringIDs, 0, stringIDNum + 1);
1930 
1931             //(13)StringTable
1932             head[INDEX_stringTable] = (short)(head[INDEX_stringIDs] + stringIDNum + 1);
1933             table_stringTable = stringTable.toString().toCharArray();
1934             //(14)
1935             head[INDEX_TABLEEND] = (short)(head[INDEX_stringTable] + stringTable.length());
1936 
1937             //StringTable cache
1938             stringCache = new String[table_stringIDs.length];
1939         }
1940 
1941         //////////////////////////////////////////////
1942         private HashMap<String, Short> scriptIDs;
1943         //elc -> Encoding.Language.Country
1944         private HashMap<String, Short> elcIDs;
1945         //componentFontNameID starts from "1", "0" reserves for "undefined"
1946         private HashMap<String, Short> componentFontNameIDs;
1947         private HashMap<String, Short> fontfileNameIDs;
1948         private HashMap<String, Integer> logicalFontIDs;
1949         private HashMap<String, Integer> fontStyleIDs;
1950 
1951         //componentFontNameID -> fontfileNameID
1952         private HashMap<Short, Short>  filenames;
1953 
1954         //elcID -> allfonts/logicalFont -> scriptID list
1955         //(1)if we have a "allfonts", then the length of the
1956         //   value array is "1", otherwise it's 5, each font
1957         //   must have their own individual entry.
1958         //scriptID list "short[]" is stored as an ID
1959         private HashMap<Short, short[]> sequences;
1960 
1961         //scriptID ->logicFontID/fontStyleID->componentFontNameID,
1962         //a 20-entry array (5-name x 4-style) for each script
1963         private HashMap<Short, Short[]> scriptFonts;
1964 
1965         //scriptID -> componentFontNameID
1966         private HashMap<Short, Short> scriptAllfonts;
1967 
1968         //scriptID -> exclusionRanges[]
1969         private HashMap<Short, int[]> exclusions;
1970 
1971         //scriptID -> fontpath
1972         private HashMap<Short, Short> awtfontpaths;
1973 
1974         //fontID -> fontID
1975         private HashMap<Short, Short> proportionals;
1976 
1977         //scriptID -> componentFontNameID
1978         private HashMap<Short, Short> scriptAllfontsMotif;
1979 
1980         //scriptID ->logicFontID/fontStyleID->componentFontNameID,
1981         private HashMap<Short, Short[]> scriptFontsMotif;
1982 
1983         //elcID -> stringID of alphabetic/XXXX
1984         private HashMap<Short, Short> alphabeticSuffix;
1985 
1986         private short[] fallbackScriptIDs;
1987         private String version;
1988         private String appendedfontpath;
1989 
1990         private void initLogicalNameStyle() {
1991             logicalFontIDs = new HashMap<String, Integer>();
1992             fontStyleIDs = new HashMap<String, Integer>();
1993             logicalFontIDs.put("serif",      0);
1994             logicalFontIDs.put("sansserif",  1);
1995             logicalFontIDs.put("monospaced", 2);
1996             logicalFontIDs.put("dialog",     3);
1997             logicalFontIDs.put("dialoginput",4);
1998             fontStyleIDs.put("plain",      0);
1999             fontStyleIDs.put("bold",       1);
2000             fontStyleIDs.put("italic",     2);
2001             fontStyleIDs.put("bolditalic", 3);
2002         }
2003 
2004         private void initHashMaps() {
2005             scriptIDs = new HashMap<String, Short>();
2006             elcIDs = new HashMap<String, Short>();
2007             componentFontNameIDs = new HashMap<String, Short>();
2008             /*Init these tables to allow componentFontNameID, fontfileNameIDs
2009               to start from "1".
2010             */
2011             componentFontNameIDs.put("", Short.valueOf((short)0));
2012 
2013             fontfileNameIDs = new HashMap<String, Short>();
2014             filenames = new HashMap<Short, Short>();
2015             sequences = new HashMap<Short, short[]>();
2016             scriptFonts = new HashMap<Short, Short[]>();
2017             scriptAllfonts = new HashMap<Short, Short>();
2018             exclusions = new HashMap<Short, int[]>();
2019             awtfontpaths = new HashMap<Short, Short>();
2020             proportionals = new HashMap<Short, Short>();
2021             scriptFontsMotif = new HashMap<Short, Short[]>();
2022             scriptAllfontsMotif = new HashMap<Short, Short>();
2023             alphabeticSuffix = new HashMap<Short, Short>();
2024             fallbackScriptIDs = EMPTY_SHORT_ARRAY;
2025             /*
2026               version
2027               appendedfontpath
2028             */
2029         }
2030 
2031         private int[] parseExclusions(String key, String exclusions) {
2032             if (exclusions == null) {
2033                 return EMPTY_INT_ARRAY;
2034             }
2035             // range format is xxxx-XXXX,yyyyyy-YYYYYY,.....
2036             int numExclusions = 1;
2037             int pos = 0;
2038             while ((pos = exclusions.indexOf(',', pos)) != -1) {
2039                 numExclusions++;
2040                 pos++;
2041             }
2042             int[] exclusionRanges = new int[numExclusions * 2];
2043             pos = 0;
2044             int newPos = 0;
2045             for (int j = 0; j < numExclusions * 2; ) {
2046                 String lower, upper;
2047                 int lo = 0, up = 0;
2048                 try {
2049                     newPos = exclusions.indexOf('-', pos);
2050                     lower = exclusions.substring(pos, newPos);
2051                     pos = newPos + 1;
2052                     newPos = exclusions.indexOf(',', pos);
2053                     if (newPos == -1) {
2054                         newPos = exclusions.length();
2055                     }
2056                     upper = exclusions.substring(pos, newPos);
2057                     pos = newPos + 1;
2058                     int lowerLength = lower.length();
2059                     int upperLength = upper.length();
2060                     if (lowerLength != 4 && lowerLength != 6
2061                         || upperLength != 4 && upperLength != 6) {
2062                         throw new Exception();
2063                     }
2064                     lo = Integer.parseInt(lower, 16);
2065                     up = Integer.parseInt(upper, 16);
2066                     if (lo > up) {
2067                         throw new Exception();
2068                     }
2069                 } catch (Exception e) {
2070                     if (FontUtilities.debugFonts() &&
2071                         logger != null) {
2072                         logger.config("Failed parsing " + key +
2073                                   " property of font configuration.");
2074 
2075                     }
2076                     return EMPTY_INT_ARRAY;
2077                 }
2078                 exclusionRanges[j++] = lo;
2079                 exclusionRanges[j++] = up;
2080             }
2081             return exclusionRanges;
2082         }
2083 
2084         private Short getID(HashMap<String, Short> map, String key) {
2085             Short ret = map.get(key);
2086             if ( ret == null) {
2087                 map.put(key, (short)map.size());
2088                 return map.get(key);
2089             }
2090             return ret;
2091         }
2092 
2093         @SuppressWarnings("serial") // JDK-implementation class
2094         class FontProperties extends Properties {
2095             public synchronized Object put(Object k, Object v) {
2096                 parseProperty((String)k, (String)v);
2097                 return null;
2098             }
2099         }
2100 
2101         private void parseProperty(String key, String value) {
2102             if (key.startsWith("filename.")) {
2103                 //the only special case is "MingLiu_HKSCS" which has "_" in its
2104                 //facename, we don't want to replace the "_" with " "
2105                 key = key.substring(9);
2106                 if (!"MingLiU_HKSCS".equals(key)) {
2107                     key = key.replace('_', ' ');
2108                 }
2109                 Short faceID = getID(componentFontNameIDs, key);
2110                 Short fileID = getID(fontfileNameIDs, value);
2111                 //System.out.println("faceID=" + faceID + "/" + key + " -> "
2112                 //    + "fileID=" + fileID + "/" + value);
2113                 filenames.put(faceID, fileID);
2114             } else if (key.startsWith("exclusion.")) {
2115                 key = key.substring(10);
2116                 exclusions.put(getID(scriptIDs,key), parseExclusions(key,value));
2117             } else if (key.startsWith("sequence.")) {
2118                 key = key.substring(9);
2119                 boolean hasDefault = false;
2120                 boolean has1252 = false;
2121 
2122                 //get the scriptID list
2123                 String[] ss = splitSequence(value).toArray(EMPTY_STRING_ARRAY);
2124                 short [] sa = new short[ss.length];
2125                 for (int i = 0; i < ss.length; i++) {
2126                     if ("alphabetic/default".equals(ss[i])) {
2127                         //System.out.println(key + " -> " + ss[i]);
2128                         ss[i] = "alphabetic";
2129                         hasDefault = true;
2130                     } else if ("alphabetic/1252".equals(ss[i])) {
2131                         //System.out.println(key + " -> " + ss[i]);
2132                         ss[i] = "alphabetic";
2133                         has1252 = true;
2134                     }
2135                     sa[i] = getID(scriptIDs, ss[i]).shortValue();
2136                     //System.out.println("scriptID=" + si[i] + "/" + ss[i]);
2137                 }
2138                 //convert the "short[] -> string -> stringID"
2139                 short scriptArrayID = getShortArrayID(sa);
2140                 Short elcID = null;
2141                 int dot = key.indexOf('.');
2142                 if (dot == -1) {
2143                     if ("fallback".equals(key)) {
2144                         fallbackScriptIDs = sa;
2145                         return;
2146                     }
2147                     if ("allfonts".equals(key)) {
2148                         elcID = getID(elcIDs, "NULL.NULL.NULL");
2149                     } else {
2150                         if (logger != null) {
2151                             logger.config("Error sequence def: <sequence." + key + ">");
2152                         }
2153                         return;
2154                     }
2155                 } else {
2156                     elcID = getID(elcIDs, key.substring(dot + 1));
2157                     //System.out.println("elcID=" + elcID + "/" + key.substring(dot + 1));
2158                     key = key.substring(0, dot);
2159                 }
2160                 short[] scriptArrayIDs = null;
2161                 if ("allfonts".equals(key)) {
2162                     scriptArrayIDs = new short[1];
2163                     scriptArrayIDs[0] = scriptArrayID;
2164                 } else {
2165                     scriptArrayIDs = sequences.get(elcID);
2166                     if (scriptArrayIDs == null) {
2167                        scriptArrayIDs = new short[5];
2168                     }
2169                     Integer fid = logicalFontIDs.get(key);
2170                     if (fid == null) {
2171                         if (logger != null) {
2172                             logger.config("Unrecognizable logicfont name " + key);
2173                         }
2174                         return;
2175                     }
2176                     //System.out.println("sequence." + key + "/" + id);
2177                     scriptArrayIDs[fid.intValue()] = scriptArrayID;
2178                 }
2179                 sequences.put(elcID, scriptArrayIDs);
2180                 if (hasDefault) {
2181                     alphabeticSuffix.put(elcID, getStringID("default"));
2182                 } else
2183                 if (has1252) {
2184                     alphabeticSuffix.put(elcID, getStringID("1252"));
2185                 }
2186             } else if (key.startsWith("allfonts.")) {
2187                 key = key.substring(9);
2188                 if (key.endsWith(".motif")) {
2189                     key = key.substring(0, key.length() - 6);
2190                     //System.out.println("motif: all." + key + "=" + value);
2191                     scriptAllfontsMotif.put(getID(scriptIDs,key), getID(componentFontNameIDs,value));
2192                 } else {
2193                     scriptAllfonts.put(getID(scriptIDs,key), getID(componentFontNameIDs,value));
2194                 }
2195             } else if (key.startsWith("awtfontpath.")) {
2196                 key = key.substring(12);
2197                 //System.out.println("scriptID=" + getID(scriptIDs, key) + "/" + key);
2198                 awtfontpaths.put(getID(scriptIDs, key), getStringID(value));
2199             } else if ("version".equals(key)) {
2200                 version = value;
2201             } else if ("appendedfontpath".equals(key)) {
2202                 appendedfontpath = value;
2203             } else if (key.startsWith("proportional.")) {
2204                 key = key.substring(13).replace('_', ' ');
2205                 //System.out.println(key + "=" + value);
2206                 proportionals.put(getID(componentFontNameIDs, key),
2207                                   getID(componentFontNameIDs, value));
2208             } else {
2209                 //"name.style.script(.motif)", we don't care anything else
2210                 int dot1, dot2;
2211                 boolean isMotif = false;
2212 
2213                 dot1 = key.indexOf('.');
2214                 if (dot1 == -1) {
2215                     if (logger != null) {
2216                         logger.config("Failed parsing " + key +
2217                                   " property of font configuration.");
2218 
2219                     }
2220                     return;
2221                 }
2222                 dot2 = key.indexOf('.', dot1 + 1);
2223                 if (dot2 == -1) {
2224                     if (logger != null) {
2225                         logger.config("Failed parsing " + key +
2226                                   " property of font configuration.");
2227 
2228                     }
2229                     return;
2230                 }
2231                 if (key.endsWith(".motif")) {
2232                     key = key.substring(0, key.length() - 6);
2233                     isMotif = true;
2234                     //System.out.println("motif: " + key + "=" + value);
2235                 }
2236                 Integer nameID = logicalFontIDs.get(key.substring(0, dot1));
2237                 Integer styleID = fontStyleIDs.get(key.substring(dot1+1, dot2));
2238                 Short scriptID = getID(scriptIDs, key.substring(dot2 + 1));
2239                 if (nameID == null || styleID == null) {
2240                     if (logger != null) {
2241                         logger.config("unrecognizable logicfont name/style at " + key);
2242                     }
2243                     return;
2244                 }
2245                 Short[] pnids;
2246                 if (isMotif) {
2247                     pnids = scriptFontsMotif.get(scriptID);
2248                 } else {
2249                     pnids = scriptFonts.get(scriptID);
2250                 }
2251                 if (pnids == null) {
2252                     pnids =  new Short[20];
2253                 }
2254                 pnids[nameID.intValue() * NUM_STYLES + styleID.intValue()]
2255                   = getID(componentFontNameIDs, value);
2256                 /*
2257                 System.out.println("key=" + key + "/<" + nameID + "><" + styleID
2258                                      + "><" + scriptID + ">=" + value
2259                                      + "/" + getID(componentFontNameIDs, value));
2260                 */
2261                 if (isMotif) {
2262                     scriptFontsMotif.put(scriptID, pnids);
2263                 } else {
2264                     scriptFonts.put(scriptID, pnids);
2265                 }
2266             }
2267         }
2268     }
2269 }
--- EOF ---