1 /*
   2  * Copyright (c) 1996, 2018, 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 ("SunOS".equals(osName)) {
1432             for (int ii = 0; ii < table_awtfontpaths.length; ii++) {
1433                 if (table_awtfontpaths[ii] == 0) {
1434                     String script = getString(table_scriptIDs[ii]);
1435                     if (script.contains("dingbats") ||
1436                         script.contains("symbol")) {
1437                         continue;
1438                     }
1439                     System.err.println("\nError: "
1440                                        + "<awtfontpath."
1441                                        + script
1442                                        + "> entry is missing!!!");
1443                     errors++;
1444                 }
1445             }
1446         }
1447         if (errors != 0) {
1448             System.err.println("!!THERE ARE " + errors + " ERROR(S) IN "
1449                                + "THE FONTCONFIG FILE, PLEASE CHECK ITS CONTENT!!\n");
1450             System.exit(1);
1451         }
1452     }
1453 
1454     private static boolean isEmpty(short[] a) {
1455         for (short s : a) {
1456             if (s != -1) {
1457                 return false;
1458             }
1459         }
1460         return true;
1461     }
1462 
1463     //dump the fontconfig data tables
1464     private static void dump() {
1465         System.out.println("\n----Head Table------------");
1466         for (int ii = 0; ii < HEAD_LENGTH; ii++) {
1467             System.out.println("  " + ii + " : " + head[ii]);
1468         }
1469         System.out.println("\n----scriptIDs-------------");
1470         printTable(table_scriptIDs, 0);
1471         System.out.println("\n----scriptFonts----------------");
1472         for (int ii = 0; ii < table_scriptIDs.length; ii++) {
1473             short fid = table_scriptFonts[ii];
1474             if (fid >= 0) {
1475                 System.out.println("  allfonts."
1476                                    + getString(table_scriptIDs[ii])
1477                                    + "="
1478                                    + getString(table_componentFontNameIDs[fid]));
1479             }
1480         }
1481         for (int ii = 0; ii < table_scriptIDs.length; ii++) {
1482             short fid = table_scriptFonts[ii];
1483             if (fid < 0) {
1484                 fid = (short)-fid;
1485                 for (int iii = 0; iii < NUM_FONTS; iii++) {
1486                     for (int iij = 0; iij < NUM_STYLES; iij++) {
1487                         int jj = iii * NUM_STYLES + iij;
1488                         short ffid = table_scriptFonts[fid + jj];
1489                         System.out.println("  "
1490                                            + getFontName(iii) + "."
1491                                            + getStyleName(iij) + "."
1492                                            + getString(table_scriptIDs[ii])
1493                                            + "="
1494                                            + getString(table_componentFontNameIDs[ffid]));
1495                     }
1496                 }
1497 
1498             }
1499         }
1500         System.out.println("\n----elcIDs----------------");
1501         printTable(table_elcIDs, 0);
1502         System.out.println("\n----sequences-------------");
1503         for (int ii = 0; ii< table_elcIDs.length; ii++) {
1504             System.out.println("  " + ii + "/" + getString(table_elcIDs[ii]));
1505             short[] ss = getShortArray(table_sequences[ii * NUM_FONTS + 0]);
1506             for (int jj = 0; jj < ss.length; jj++) {
1507                 System.out.println("     " + getString(table_scriptIDs[ss[jj]]));
1508             }
1509         }
1510         System.out.println("\n----fontfileNameIDs-------");
1511         printTable(table_fontfileNameIDs, 0);
1512 
1513         System.out.println("\n----componentFontNameIDs--");
1514         printTable(table_componentFontNameIDs, 1);
1515         System.out.println("\n----filenames-------------");
1516         for (int ii = 0; ii < table_filenames.length; ii++) {
1517             if (table_filenames[ii] == -1) {
1518                 System.out.println("  " + ii + " : null");
1519             } else {
1520                 System.out.println("  " + ii + " : "
1521                    + getString(table_fontfileNameIDs[table_filenames[ii]]));
1522             }
1523         }
1524         System.out.println("\n----awtfontpaths---------");
1525         for (int ii = 0; ii < table_awtfontpaths.length; ii++) {
1526             System.out.println("  " + getString(table_scriptIDs[ii])
1527                                + " : "
1528                                + getString(table_awtfontpaths[ii]));
1529         }
1530         System.out.println("\n----proportionals--------");
1531         for (int ii = 0; ii < table_proportionals.length; ii++) {
1532             System.out.println("  "
1533                    + getString(table_componentFontNameIDs[table_proportionals[ii++]])
1534                    + " -> "
1535                    + getString(table_componentFontNameIDs[table_proportionals[ii]]));
1536         }
1537         int i = 0;
1538         System.out.println("\n----alphabeticSuffix----");
1539         while (i < table_alphabeticSuffix.length) {
1540           System.out.println("    " + getString(table_elcIDs[table_alphabeticSuffix[i++]])
1541                              + " -> " + getString(table_alphabeticSuffix[i++]));
1542         }
1543         System.out.println("\n----String Table---------");
1544         System.out.println("    stringID:    Num =" + table_stringIDs.length);
1545         System.out.println("    stringTable: Size=" + table_stringTable.length * 2);
1546 
1547         System.out.println("\n----fallbackScriptIDs---");
1548         short[] fbsIDs = getShortArray(head[INDEX_fallbackScripts]);
1549         for (int ii = 0; ii < fbsIDs.length; ii++) {
1550           System.out.println("  " + getString(table_scriptIDs[fbsIDs[ii]]));
1551         }
1552         System.out.println("\n----appendedfontpath-----");
1553         System.out.println("  " + getString(head[INDEX_appendedfontpath]));
1554         System.out.println("\n----Version--------------");
1555         System.out.println("  " + getString(head[INDEX_version]));
1556     }
1557 
1558 
1559     //////////////////////////////////////////////////////////////////////
1560     // Data table access methods                                        //
1561     //////////////////////////////////////////////////////////////////////
1562 
1563     /* Return the fontID of the platformFontName defined in this font config
1564      * by "LogicalFontName.StyleName.CharacterSubsetName" entry or
1565      * "allfonts.CharacterSubsetName" entry in properties format fc file.
1566      */
1567     protected static short getComponentFontID(short scriptID, int fontIndex, int styleIndex) {
1568         short fid = table_scriptFonts[scriptID];
1569         //System.out.println("fid=" + fid + "/ scriptID=" + scriptID + ", fi=" + fontIndex + ", si=" + styleIndex);
1570         if (fid >= 0) {
1571             //"allfonts"
1572             return fid;
1573         } else {
1574             return table_scriptFonts[-fid + fontIndex * NUM_STYLES + styleIndex];
1575         }
1576     }
1577 
1578     /* Same as getCompoentFontID() except this method returns the fontID define by
1579      * "xxxx.motif" entry.
1580      */
1581     protected static short getComponentFontIDMotif(short scriptID, int fontIndex, int styleIndex) {
1582         if (table_scriptFontsMotif.length == 0) {
1583             return 0;
1584         }
1585         short fid = table_scriptFontsMotif[scriptID];
1586         if (fid >= 0) {
1587             //"allfonts" > 0 or "not defined" == 0
1588             return fid;
1589         } else {
1590             return table_scriptFontsMotif[-fid + fontIndex * NUM_STYLES + styleIndex];
1591         }
1592     }
1593 
1594     private static int[] getExclusionRanges(short scriptID) {
1595         short exID = table_exclusions[scriptID];
1596         if (exID == 0) {
1597             return EMPTY_INT_ARRAY;
1598         } else {
1599             char[] exChar = getString(exID).toCharArray();
1600             int[] exInt = new int[exChar.length / 2];
1601             int i = 0;
1602             for (int j = 0; j < exInt.length; j++) {
1603                 exInt[j] = (exChar[i++] << 16) + (exChar[i++] & 0xffff);
1604             }
1605             return exInt;
1606         }
1607     }
1608 
1609     private static boolean contains(short[] IDs, short id, int limit) {
1610         for (int i = 0; i < limit; i++) {
1611             if (IDs[i] == id) {
1612                 return true;
1613             }
1614         }
1615         return false;
1616     }
1617 
1618     /* Return the PlatformFontName from its fontID*/
1619     protected static String getComponentFontName(short id) {
1620         if (id < 0) {
1621             return null;
1622         }
1623         return getString(table_componentFontNameIDs[id]);
1624     }
1625 
1626     private static String getComponentFileName(short id) {
1627         if (id < 0) {
1628             return null;
1629         }
1630         return getString(table_fontfileNameIDs[id]);
1631     }
1632 
1633     //componentFontID -> componentFileID
1634     private static short getComponentFileID(short nameID) {
1635         return table_filenames[nameID];
1636     }
1637 
1638     private static String getScriptName(short scriptID) {
1639         return getString(table_scriptIDs[scriptID]);
1640     }
1641 
1642    private HashMap<String, Short> reorderScripts;
1643    protected short[] getCoreScripts(int fontIndex) {
1644         short elc = getInitELC();
1645         /*
1646           System.out.println("getCoreScripts: elc=" + elc + ", fontIndex=" + fontIndex);
1647           short[] ss = getShortArray(table_sequences[elc * NUM_FONTS + fontIndex]);
1648           for (int i = 0; i < ss.length; i++) {
1649               System.out.println("     " + getString((short)table_scriptIDs[ss[i]]));
1650           }
1651           */
1652         short[] scripts = getShortArray(table_sequences[elc * NUM_FONTS + fontIndex]);
1653         if (preferLocaleFonts) {
1654             if (reorderScripts == null) {
1655                 reorderScripts = new HashMap<String, Short>();
1656             }
1657             String[] ss = new String[scripts.length];
1658             for (int i = 0; i < ss.length; i++) {
1659                 ss[i] = getScriptName(scripts[i]);
1660                 reorderScripts.put(ss[i], scripts[i]);
1661             }
1662             reorderSequenceForLocale(ss);
1663             for (int i = 0; i < ss.length; i++) {
1664                 scripts[i] = reorderScripts.get(ss[i]);
1665             }
1666         }
1667          return scripts;
1668     }
1669 
1670     private static short[] getFallbackScripts() {
1671         return getShortArray(head[INDEX_fallbackScripts]);
1672     }
1673 
1674     private static void printTable(short[] list, int start) {
1675         for (int i = start; i < list.length; i++) {
1676             System.out.println("  " + i + " : " + getString(list[i]));
1677         }
1678     }
1679 
1680     private static short[] readShortTable(DataInputStream in, int len )
1681         throws IOException {
1682         if (len == 0) {
1683             return EMPTY_SHORT_ARRAY;
1684         }
1685         short[] data = new short[len];
1686         byte[] bb = new byte[len * 2];
1687         in.read(bb);
1688         int i = 0,j = 0;
1689         while (i < len) {
1690             data[i++] = (short)(bb[j++] << 8 | (bb[j++] & 0xff));
1691         }
1692         return data;
1693     }
1694 
1695     private static void writeShortTable(DataOutputStream out, short[] data)
1696         throws IOException {
1697         for (short val : data) {
1698             out.writeShort(val);
1699         }
1700     }
1701 
1702     private static short[] toList(HashMap<String, Short> map) {
1703         short[] list = new short[map.size()];
1704         Arrays.fill(list, (short) -1);
1705         for (Entry<String, Short> entry : map.entrySet()) {
1706             list[entry.getValue()] = getStringID(entry.getKey());
1707         }
1708         return list;
1709     }
1710 
1711     //runtime cache
1712     private static String[] stringCache;
1713     protected static String getString(short stringID) {
1714         if (stringID == 0)
1715             return null;
1716         /*
1717         if (loadingProperties) {
1718             return stringTable.substring(stringIDs[stringID],
1719                                          stringIDs[stringID+1]);
1720         }
1721         */
1722         //sync if we want it to be MT-enabled
1723         if (stringCache[stringID] == null){
1724             stringCache[stringID] =
1725               new String (table_stringTable,
1726                           table_stringIDs[stringID],
1727                           table_stringIDs[stringID+1] - table_stringIDs[stringID]);
1728         }
1729         return stringCache[stringID];
1730     }
1731 
1732     private static short[] getShortArray(short shortArrayID) {
1733         String s = getString(shortArrayID);
1734         char[] cc = s.toCharArray();
1735         short[] ss = new short[cc.length];
1736         for (int i = 0; i < cc.length; i++) {
1737             ss[i] = (short)(cc[i] & 0xffff);
1738         }
1739         return ss;
1740     }
1741 
1742     private static short getStringID(String s) {
1743         if (s == null) {
1744             return (short)0;
1745         }
1746         short pos0 = (short)stringTable.length();
1747         stringTable.append(s);
1748         short pos1 = (short)stringTable.length();
1749 
1750         stringIDs[stringIDNum] = pos0;
1751         stringIDs[stringIDNum + 1] = pos1;
1752         stringIDNum++;
1753         if (stringIDNum + 1 >= stringIDs.length) {
1754             short[] tmp = new short[stringIDNum + 1000];
1755             System.arraycopy(stringIDs, 0, tmp, 0, stringIDNum);
1756             stringIDs = tmp;
1757         }
1758         return (short)(stringIDNum - 1);
1759     }
1760 
1761     private static short getShortArrayID(short[] sa) {
1762         char[] cc = new char[sa.length];
1763         for (int i = 0; i < sa.length; i ++) {
1764             cc[i] = (char)sa[i];
1765         }
1766         String s = new String(cc);
1767         return getStringID(s);
1768     }
1769 
1770     //utility "empty" objects
1771     private static final int[] EMPTY_INT_ARRAY = new int[0];
1772     private static final String[] EMPTY_STRING_ARRAY = new String[0];
1773     private static final short[] EMPTY_SHORT_ARRAY = new short[0];
1774     private static final String UNDEFINED_COMPONENT_FONT = "unknown";
1775 
1776     //////////////////////////////////////////////////////////////////////////
1777     //Convert the FontConfig data in Properties file to binary data tables  //
1778     //////////////////////////////////////////////////////////////////////////
1779     static class PropertiesHandler {
1780         public void load(InputStream in) throws IOException {
1781             initLogicalNameStyle();
1782             initHashMaps();
1783             FontProperties fp = new FontProperties();
1784             fp.load(in);
1785             initBinaryTable();
1786         }
1787 
1788         private void initBinaryTable() {
1789             //(0)
1790             head = new short[HEAD_LENGTH];
1791             head[INDEX_scriptIDs] = (short)HEAD_LENGTH;
1792 
1793             table_scriptIDs = toList(scriptIDs);
1794             //(1)a: scriptAllfonts scriptID/allfonts -> componentFontNameID
1795             //   b: scriptFonts    scriptID -> componentFontNameID[20]
1796             //if we have a "allfonts.script" def, then we just put
1797             //the "-platformFontID" value in the slot, otherwise the slot
1798             //value is "offset" which "offset" is where 20 entries located
1799             //in the table attached.
1800             head[INDEX_scriptFonts] = (short)(head[INDEX_scriptIDs]  + table_scriptIDs.length);
1801             int len = table_scriptIDs.length + scriptFonts.size() * 20;
1802             table_scriptFonts = new short[len];
1803 
1804             for (Entry<Short, Short> entry : scriptAllfonts.entrySet()) {
1805                 table_scriptFonts[entry.getKey().intValue()] = entry.getValue();
1806             }
1807             int off = table_scriptIDs.length;
1808             for (Entry<Short, Short[]> entry : scriptFonts.entrySet()) {
1809                 table_scriptFonts[entry.getKey().intValue()] = (short)-off;
1810                 Short[] v = entry.getValue();
1811                 for (int i = 0; i < 20; i++) {
1812                     if (v[i] != null) {
1813                         table_scriptFonts[off++] = v[i];
1814                     } else {
1815                         table_scriptFonts[off++] = 0;
1816                     }
1817                 }
1818             }
1819 
1820             //(2)
1821             head[INDEX_elcIDs] = (short)(head[INDEX_scriptFonts]  + table_scriptFonts.length);
1822             table_elcIDs = toList(elcIDs);
1823 
1824             //(3) sequences  elcID -> XXXX[1|5] -> scriptID[]
1825             head[INDEX_sequences] = (short)(head[INDEX_elcIDs]  + table_elcIDs.length);
1826             table_sequences = new short[elcIDs.size() * NUM_FONTS];
1827             for (Entry<Short, short[]> entry : sequences.entrySet()) {
1828                 //table_sequences[entry.getKey().intValue()] = (short)-off;
1829                 int k = entry.getKey().intValue();
1830                 short[] v = entry.getValue();
1831                 /*
1832                   System.out.println("elc=" + k + "/" + getString((short)table_elcIDs[k]));
1833                   short[] ss = getShortArray(v[0]);
1834                   for (int i = 0; i < ss.length; i++) {
1835                   System.out.println("     " + getString((short)table_scriptIDs[ss[i]]));
1836                   }
1837                   */
1838                 if (v.length == 1) {
1839                     //the "allfonts" entries
1840                     for (int i = 0; i < NUM_FONTS; i++) {
1841                         table_sequences[k * NUM_FONTS + i] = v[0];
1842                     }
1843                 } else {
1844                     for (int i = 0; i < NUM_FONTS; i++) {
1845                         table_sequences[k * NUM_FONTS + i] = v[i];
1846                     }
1847                 }
1848             }
1849             //(4)
1850             head[INDEX_fontfileNameIDs] = (short)(head[INDEX_sequences]  + table_sequences.length);
1851             table_fontfileNameIDs = toList(fontfileNameIDs);
1852 
1853             //(5)
1854             head[INDEX_componentFontNameIDs] = (short)(head[INDEX_fontfileNameIDs]  + table_fontfileNameIDs.length);
1855             table_componentFontNameIDs = toList(componentFontNameIDs);
1856 
1857             //(6)componentFontNameID -> filenameID
1858             head[INDEX_filenames] = (short)(head[INDEX_componentFontNameIDs]  + table_componentFontNameIDs.length);
1859             table_filenames = new short[table_componentFontNameIDs.length];
1860             Arrays.fill(table_filenames, (short) -1);
1861 
1862             for (Entry<Short, Short> entry : filenames.entrySet()) {
1863                 table_filenames[entry.getKey()] = entry.getValue();
1864             }
1865 
1866             //(7)scriptID-> awtfontpath
1867             //the paths are stored as scriptID -> stringID in awtfontpahts
1868             head[INDEX_awtfontpaths] = (short)(head[INDEX_filenames]  + table_filenames.length);
1869             table_awtfontpaths = new short[table_scriptIDs.length];
1870             for (Entry<Short, Short> entry : awtfontpaths.entrySet()) {
1871                 table_awtfontpaths[entry.getKey()] = entry.getValue();
1872             }
1873 
1874             //(8)exclusions
1875             head[INDEX_exclusions] = (short)(head[INDEX_awtfontpaths]  + table_awtfontpaths.length);
1876             table_exclusions = new short[scriptIDs.size()];
1877             for (Entry<Short, int[]> entry : exclusions.entrySet()) {
1878                 int[] exI = entry.getValue();
1879                 char[] exC = new char[exI.length * 2];
1880                 int j = 0;
1881                 for (int i = 0; i < exI.length; i++) {
1882                     exC[j++] = (char) (exI[i] >> 16);
1883                     exC[j++] = (char) (exI[i] & 0xffff);
1884                 }
1885                 table_exclusions[entry.getKey()] = getStringID(new String (exC));
1886             }
1887             //(9)proportionals
1888             head[INDEX_proportionals] = (short)(head[INDEX_exclusions]  + table_exclusions.length);
1889             table_proportionals = new short[proportionals.size() * 2];
1890             int j = 0;
1891             for (Entry<Short, Short> entry : proportionals.entrySet()) {
1892                 table_proportionals[j++] = entry.getKey();
1893                 table_proportionals[j++] = entry.getValue();
1894             }
1895 
1896             //(10) see (1) for info, the only difference is "xxx.motif"
1897             head[INDEX_scriptFontsMotif] = (short)(head[INDEX_proportionals] + table_proportionals.length);
1898             if (scriptAllfontsMotif.size() != 0 || scriptFontsMotif.size() != 0) {
1899                 len = table_scriptIDs.length + scriptFontsMotif.size() * 20;
1900                 table_scriptFontsMotif = new short[len];
1901 
1902                 for (Entry<Short, Short> entry : scriptAllfontsMotif.entrySet()) {
1903                     table_scriptFontsMotif[entry.getKey().intValue()] =
1904                       (short)entry.getValue();
1905                 }
1906                 off = table_scriptIDs.length;
1907                 for (Entry<Short, Short[]> entry : scriptFontsMotif.entrySet()) {
1908                     table_scriptFontsMotif[entry.getKey().intValue()] = (short)-off;
1909                     Short[] v = entry.getValue();
1910                     int i = 0;
1911                     while (i < 20) {
1912                         if (v[i] != null) {
1913                             table_scriptFontsMotif[off++] = v[i];
1914                         } else {
1915                             table_scriptFontsMotif[off++] = 0;
1916                         }
1917                         i++;
1918                     }
1919                 }
1920             } else {
1921                 table_scriptFontsMotif = EMPTY_SHORT_ARRAY;
1922             }
1923 
1924             //(11)short[] alphabeticSuffix
1925             head[INDEX_alphabeticSuffix] = (short)(head[INDEX_scriptFontsMotif] + table_scriptFontsMotif.length);
1926             table_alphabeticSuffix = new short[alphabeticSuffix.size() * 2];
1927             j = 0;
1928             for (Entry<Short, Short> entry : alphabeticSuffix.entrySet()) {
1929                 table_alphabeticSuffix[j++] = entry.getKey();
1930                 table_alphabeticSuffix[j++] = entry.getValue();
1931             }
1932 
1933             //(15)short[] fallbackScriptIDs; just put the ID in head
1934             head[INDEX_fallbackScripts] = getShortArrayID(fallbackScriptIDs);
1935 
1936             //(16)appendedfontpath
1937             head[INDEX_appendedfontpath] = getStringID(appendedfontpath);
1938 
1939             //(17)version
1940             head[INDEX_version] = getStringID(version);
1941 
1942             //(12)short[] StringIDs
1943             head[INDEX_stringIDs] = (short)(head[INDEX_alphabeticSuffix] + table_alphabeticSuffix.length);
1944             table_stringIDs = new short[stringIDNum + 1];
1945             System.arraycopy(stringIDs, 0, table_stringIDs, 0, stringIDNum + 1);
1946 
1947             //(13)StringTable
1948             head[INDEX_stringTable] = (short)(head[INDEX_stringIDs] + stringIDNum + 1);
1949             table_stringTable = stringTable.toString().toCharArray();
1950             //(14)
1951             head[INDEX_TABLEEND] = (short)(head[INDEX_stringTable] + stringTable.length());
1952 
1953             //StringTable cache
1954             stringCache = new String[table_stringIDs.length];
1955         }
1956 
1957         //////////////////////////////////////////////
1958         private HashMap<String, Short> scriptIDs;
1959         //elc -> Encoding.Language.Country
1960         private HashMap<String, Short> elcIDs;
1961         //componentFontNameID starts from "1", "0" reserves for "undefined"
1962         private HashMap<String, Short> componentFontNameIDs;
1963         private HashMap<String, Short> fontfileNameIDs;
1964         private HashMap<String, Integer> logicalFontIDs;
1965         private HashMap<String, Integer> fontStyleIDs;
1966 
1967         //componentFontNameID -> fontfileNameID
1968         private HashMap<Short, Short>  filenames;
1969 
1970         //elcID -> allfonts/logicalFont -> scriptID list
1971         //(1)if we have a "allfonts", then the length of the
1972         //   value array is "1", otherwise it's 5, each font
1973         //   must have their own individual entry.
1974         //scriptID list "short[]" is stored as an ID
1975         private HashMap<Short, short[]> sequences;
1976 
1977         //scriptID ->logicFontID/fontStyleID->componentFontNameID,
1978         //a 20-entry array (5-name x 4-style) for each script
1979         private HashMap<Short, Short[]> scriptFonts;
1980 
1981         //scriptID -> componentFontNameID
1982         private HashMap<Short, Short> scriptAllfonts;
1983 
1984         //scriptID -> exclusionRanges[]
1985         private HashMap<Short, int[]> exclusions;
1986 
1987         //scriptID -> fontpath
1988         private HashMap<Short, Short> awtfontpaths;
1989 
1990         //fontID -> fontID
1991         private HashMap<Short, Short> proportionals;
1992 
1993         //scriptID -> componentFontNameID
1994         private HashMap<Short, Short> scriptAllfontsMotif;
1995 
1996         //scriptID ->logicFontID/fontStyleID->componentFontNameID,
1997         private HashMap<Short, Short[]> scriptFontsMotif;
1998 
1999         //elcID -> stringID of alphabetic/XXXX
2000         private HashMap<Short, Short> alphabeticSuffix;
2001 
2002         private short[] fallbackScriptIDs;
2003         private String version;
2004         private String appendedfontpath;
2005 
2006         private void initLogicalNameStyle() {
2007             logicalFontIDs = new HashMap<String, Integer>();
2008             fontStyleIDs = new HashMap<String, Integer>();
2009             logicalFontIDs.put("serif",      0);
2010             logicalFontIDs.put("sansserif",  1);
2011             logicalFontIDs.put("monospaced", 2);
2012             logicalFontIDs.put("dialog",     3);
2013             logicalFontIDs.put("dialoginput",4);
2014             fontStyleIDs.put("plain",      0);
2015             fontStyleIDs.put("bold",       1);
2016             fontStyleIDs.put("italic",     2);
2017             fontStyleIDs.put("bolditalic", 3);
2018         }
2019 
2020         private void initHashMaps() {
2021             scriptIDs = new HashMap<String, Short>();
2022             elcIDs = new HashMap<String, Short>();
2023             componentFontNameIDs = new HashMap<String, Short>();
2024             /*Init these tables to allow componentFontNameID, fontfileNameIDs
2025               to start from "1".
2026             */
2027             componentFontNameIDs.put("", Short.valueOf((short)0));
2028 
2029             fontfileNameIDs = new HashMap<String, Short>();
2030             filenames = new HashMap<Short, Short>();
2031             sequences = new HashMap<Short, short[]>();
2032             scriptFonts = new HashMap<Short, Short[]>();
2033             scriptAllfonts = new HashMap<Short, Short>();
2034             exclusions = new HashMap<Short, int[]>();
2035             awtfontpaths = new HashMap<Short, Short>();
2036             proportionals = new HashMap<Short, Short>();
2037             scriptFontsMotif = new HashMap<Short, Short[]>();
2038             scriptAllfontsMotif = new HashMap<Short, Short>();
2039             alphabeticSuffix = new HashMap<Short, Short>();
2040             fallbackScriptIDs = EMPTY_SHORT_ARRAY;
2041             /*
2042               version
2043               appendedfontpath
2044             */
2045         }
2046 
2047         private int[] parseExclusions(String key, String exclusions) {
2048             if (exclusions == null) {
2049                 return EMPTY_INT_ARRAY;
2050             }
2051             // range format is xxxx-XXXX,yyyyyy-YYYYYY,.....
2052             int numExclusions = 1;
2053             int pos = 0;
2054             while ((pos = exclusions.indexOf(',', pos)) != -1) {
2055                 numExclusions++;
2056                 pos++;
2057             }
2058             int[] exclusionRanges = new int[numExclusions * 2];
2059             pos = 0;
2060             int newPos = 0;
2061             for (int j = 0; j < numExclusions * 2; ) {
2062                 String lower, upper;
2063                 int lo = 0, up = 0;
2064                 try {
2065                     newPos = exclusions.indexOf('-', pos);
2066                     lower = exclusions.substring(pos, newPos);
2067                     pos = newPos + 1;
2068                     newPos = exclusions.indexOf(',', pos);
2069                     if (newPos == -1) {
2070                         newPos = exclusions.length();
2071                     }
2072                     upper = exclusions.substring(pos, newPos);
2073                     pos = newPos + 1;
2074                     int lowerLength = lower.length();
2075                     int upperLength = upper.length();
2076                     if (lowerLength != 4 && lowerLength != 6
2077                         || upperLength != 4 && upperLength != 6) {
2078                         throw new Exception();
2079                     }
2080                     lo = Integer.parseInt(lower, 16);
2081                     up = Integer.parseInt(upper, 16);
2082                     if (lo > up) {
2083                         throw new Exception();
2084                     }
2085                 } catch (Exception e) {
2086                     if (FontUtilities.debugFonts() &&
2087                         logger != null) {
2088                         logger.config("Failed parsing " + key +
2089                                   " property of font configuration.");
2090 
2091                     }
2092                     return EMPTY_INT_ARRAY;
2093                 }
2094                 exclusionRanges[j++] = lo;
2095                 exclusionRanges[j++] = up;
2096             }
2097             return exclusionRanges;
2098         }
2099 
2100         private Short getID(HashMap<String, Short> map, String key) {
2101             Short ret = map.get(key);
2102             if ( ret == null) {
2103                 map.put(key, (short)map.size());
2104                 return map.get(key);
2105             }
2106             return ret;
2107         }
2108 
2109         @SuppressWarnings("serial") // JDK-implementation class
2110         class FontProperties extends Properties {
2111             public synchronized Object put(Object k, Object v) {
2112                 parseProperty((String)k, (String)v);
2113                 return null;
2114             }
2115         }
2116 
2117         private void parseProperty(String key, String value) {
2118             if (key.startsWith("filename.")) {
2119                 //the only special case is "MingLiu_HKSCS" which has "_" in its
2120                 //facename, we don't want to replace the "_" with " "
2121                 key = key.substring(9);
2122                 if (!"MingLiU_HKSCS".equals(key)) {
2123                     key = key.replace('_', ' ');
2124                 }
2125                 Short faceID = getID(componentFontNameIDs, key);
2126                 Short fileID = getID(fontfileNameIDs, value);
2127                 //System.out.println("faceID=" + faceID + "/" + key + " -> "
2128                 //    + "fileID=" + fileID + "/" + value);
2129                 filenames.put(faceID, fileID);
2130             } else if (key.startsWith("exclusion.")) {
2131                 key = key.substring(10);
2132                 exclusions.put(getID(scriptIDs,key), parseExclusions(key,value));
2133             } else if (key.startsWith("sequence.")) {
2134                 key = key.substring(9);
2135                 boolean hasDefault = false;
2136                 boolean has1252 = false;
2137 
2138                 //get the scriptID list
2139                 String[] ss = splitSequence(value).toArray(EMPTY_STRING_ARRAY);
2140                 short [] sa = new short[ss.length];
2141                 for (int i = 0; i < ss.length; i++) {
2142                     if ("alphabetic/default".equals(ss[i])) {
2143                         //System.out.println(key + " -> " + ss[i]);
2144                         ss[i] = "alphabetic";
2145                         hasDefault = true;
2146                     } else if ("alphabetic/1252".equals(ss[i])) {
2147                         //System.out.println(key + " -> " + ss[i]);
2148                         ss[i] = "alphabetic";
2149                         has1252 = true;
2150                     }
2151                     sa[i] = getID(scriptIDs, ss[i]).shortValue();
2152                     //System.out.println("scriptID=" + si[i] + "/" + ss[i]);
2153                 }
2154                 //convert the "short[] -> string -> stringID"
2155                 short scriptArrayID = getShortArrayID(sa);
2156                 Short elcID = null;
2157                 int dot = key.indexOf('.');
2158                 if (dot == -1) {
2159                     if ("fallback".equals(key)) {
2160                         fallbackScriptIDs = sa;
2161                         return;
2162                     }
2163                     if ("allfonts".equals(key)) {
2164                         elcID = getID(elcIDs, "NULL.NULL.NULL");
2165                     } else {
2166                         if (logger != null) {
2167                             logger.config("Error sequence def: <sequence." + key + ">");
2168                         }
2169                         return;
2170                     }
2171                 } else {
2172                     elcID = getID(elcIDs, key.substring(dot + 1));
2173                     //System.out.println("elcID=" + elcID + "/" + key.substring(dot + 1));
2174                     key = key.substring(0, dot);
2175                 }
2176                 short[] scriptArrayIDs = null;
2177                 if ("allfonts".equals(key)) {
2178                     scriptArrayIDs = new short[1];
2179                     scriptArrayIDs[0] = scriptArrayID;
2180                 } else {
2181                     scriptArrayIDs = sequences.get(elcID);
2182                     if (scriptArrayIDs == null) {
2183                        scriptArrayIDs = new short[5];
2184                     }
2185                     Integer fid = logicalFontIDs.get(key);
2186                     if (fid == null) {
2187                         if (logger != null) {
2188                             logger.config("Unrecognizable logicfont name " + key);
2189                         }
2190                         return;
2191                     }
2192                     //System.out.println("sequence." + key + "/" + id);
2193                     scriptArrayIDs[fid.intValue()] = scriptArrayID;
2194                 }
2195                 sequences.put(elcID, scriptArrayIDs);
2196                 if (hasDefault) {
2197                     alphabeticSuffix.put(elcID, getStringID("default"));
2198                 } else
2199                 if (has1252) {
2200                     alphabeticSuffix.put(elcID, getStringID("1252"));
2201                 }
2202             } else if (key.startsWith("allfonts.")) {
2203                 key = key.substring(9);
2204                 if (key.endsWith(".motif")) {
2205                     key = key.substring(0, key.length() - 6);
2206                     //System.out.println("motif: all." + key + "=" + value);
2207                     scriptAllfontsMotif.put(getID(scriptIDs,key), getID(componentFontNameIDs,value));
2208                 } else {
2209                     scriptAllfonts.put(getID(scriptIDs,key), getID(componentFontNameIDs,value));
2210                 }
2211             } else if (key.startsWith("awtfontpath.")) {
2212                 key = key.substring(12);
2213                 //System.out.println("scriptID=" + getID(scriptIDs, key) + "/" + key);
2214                 awtfontpaths.put(getID(scriptIDs, key), getStringID(value));
2215             } else if ("version".equals(key)) {
2216                 version = value;
2217             } else if ("appendedfontpath".equals(key)) {
2218                 appendedfontpath = value;
2219             } else if (key.startsWith("proportional.")) {
2220                 key = key.substring(13).replace('_', ' ');
2221                 //System.out.println(key + "=" + value);
2222                 proportionals.put(getID(componentFontNameIDs, key),
2223                                   getID(componentFontNameIDs, value));
2224             } else {
2225                 //"name.style.script(.motif)", we don't care anything else
2226                 int dot1, dot2;
2227                 boolean isMotif = false;
2228 
2229                 dot1 = key.indexOf('.');
2230                 if (dot1 == -1) {
2231                     if (logger != null) {
2232                         logger.config("Failed parsing " + key +
2233                                   " property of font configuration.");
2234 
2235                     }
2236                     return;
2237                 }
2238                 dot2 = key.indexOf('.', dot1 + 1);
2239                 if (dot2 == -1) {
2240                     if (logger != null) {
2241                         logger.config("Failed parsing " + key +
2242                                   " property of font configuration.");
2243 
2244                     }
2245                     return;
2246                 }
2247                 if (key.endsWith(".motif")) {
2248                     key = key.substring(0, key.length() - 6);
2249                     isMotif = true;
2250                     //System.out.println("motif: " + key + "=" + value);
2251                 }
2252                 Integer nameID = logicalFontIDs.get(key.substring(0, dot1));
2253                 Integer styleID = fontStyleIDs.get(key.substring(dot1+1, dot2));
2254                 Short scriptID = getID(scriptIDs, key.substring(dot2 + 1));
2255                 if (nameID == null || styleID == null) {
2256                     if (logger != null) {
2257                         logger.config("unrecognizable logicfont name/style at " + key);
2258                     }
2259                     return;
2260                 }
2261                 Short[] pnids;
2262                 if (isMotif) {
2263                     pnids = scriptFontsMotif.get(scriptID);
2264                 } else {
2265                     pnids = scriptFonts.get(scriptID);
2266                 }
2267                 if (pnids == null) {
2268                     pnids =  new Short[20];
2269                 }
2270                 pnids[nameID.intValue() * NUM_STYLES + styleID.intValue()]
2271                   = getID(componentFontNameIDs, value);
2272                 /*
2273                 System.out.println("key=" + key + "/<" + nameID + "><" + styleID
2274                                      + "><" + scriptID + ">=" + value
2275                                      + "/" + getID(componentFontNameIDs, value));
2276                 */
2277                 if (isMotif) {
2278                     scriptFontsMotif.put(scriptID, pnids);
2279                 } else {
2280                     scriptFonts.put(scriptID, pnids);
2281                 }
2282             }
2283         }
2284     }
2285 }