/src/share/classes/sun/awt/FontConfiguration.java
Java | 2287 lines | 1648 code | 191 blank | 448 comment | 394 complexity | 3461265e645d057859758ca155b1d540 MD5 | raw file
Possible License(s): BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0, GPL-2.0
Large files files are truncated, but you can click here to view the full file
- /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
- package sun.awt;
- import java.awt.Font;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.nio.charset.Charset;
- import java.nio.charset.CharsetEncoder;
- import java.security.AccessController;
- import java.security.PrivilegedAction;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Hashtable;
- import java.util.Locale;
- import java.util.Map.Entry;
- import java.util.Properties;
- import java.util.Set;
- import java.util.Vector;
- import sun.font.CompositeFontDescriptor;
- import sun.font.SunFontManager;
- import sun.font.FontManagerFactory;
- import sun.font.FontUtilities;
- import sun.util.logging.PlatformLogger;
- /**
- * Provides the definitions of the five logical fonts: Serif, SansSerif,
- * Monospaced, Dialog, and DialogInput. The necessary information
- * is obtained from fontconfig files.
- */
- public abstract class FontConfiguration {
- //static global runtime env
- protected static String osVersion;
- protected static String osName;
- protected static String encoding; // canonical name of default nio charset
- protected static Locale startupLocale = null;
- protected static Hashtable localeMap = null;
- private static FontConfiguration fontConfig;
- private static PlatformLogger logger;
- protected static boolean isProperties = true;
- protected SunFontManager fontManager;
- protected boolean preferLocaleFonts;
- protected boolean preferPropFonts;
- private File fontConfigFile;
- private boolean foundOsSpecificFile;
- private boolean inited;
- private String javaLib;
- /* A default FontConfiguration must be created before an alternate
- * one to ensure proper static initialisation takes place.
- */
- public FontConfiguration(SunFontManager fm) {
- if (FontUtilities.debugFonts()) {
- FontUtilities.getLogger()
- .info("Creating standard Font Configuration");
- }
- if (FontUtilities.debugFonts() && logger == null) {
- logger = PlatformLogger.getLogger("sun.awt.FontConfiguration");
- }
- fontManager = fm;
- setOsNameAndVersion(); /* static initialization */
- setEncoding(); /* static initialization */
- /* Separating out the file location from the rest of the
- * initialisation, so the caller has the option of doing
- * something else if a suitable file isn't found.
- */
- findFontConfigFile();
- }
- public synchronized boolean init() {
- if (!inited) {
- this.preferLocaleFonts = false;
- this.preferPropFonts = false;
- setFontConfiguration();
- readFontConfigFile(fontConfigFile);
- initFontConfig();
- inited = true;
- }
- return true;
- }
- public FontConfiguration(SunFontManager fm,
- boolean preferLocaleFonts,
- boolean preferPropFonts) {
- fontManager = fm;
- if (FontUtilities.debugFonts()) {
- FontUtilities.getLogger()
- .info("Creating alternate Font Configuration");
- }
- this.preferLocaleFonts = preferLocaleFonts;
- this.preferPropFonts = preferPropFonts;
- /* fontConfig should be initialised by default constructor, and
- * its data tables can be shared, since readFontConfigFile doesn't
- * update any other state. Also avoid a doPrivileged block.
- */
- initFontConfig();
- }
- /**
- * Fills in this instance's osVersion and osName members. By
- * default uses the system properties os.name and os.version;
- * subclasses may override.
- */
- protected void setOsNameAndVersion() {
- osName = System.getProperty("os.name");
- osVersion = System.getProperty("os.version");
- }
- private void setEncoding() {
- encoding = Charset.defaultCharset().name();
- startupLocale = SunToolkit.getStartupLocale();
- }
- /////////////////////////////////////////////////////////////////////
- // methods for loading the FontConfig file //
- /////////////////////////////////////////////////////////////////////
- public boolean foundOsSpecificFile() {
- return foundOsSpecificFile;
- }
- /* Smoke test to see if we can trust this configuration by testing if
- * the first slot of a composite font maps to an installed file.
- */
- public boolean fontFilesArePresent() {
- init();
- short fontNameID = compFontNameIDs[0][0][0];
- short fileNameID = getComponentFileID(fontNameID);
- final String fileName = mapFileName(getComponentFileName(fileNameID));
- Boolean exists = (Boolean)java.security.AccessController.doPrivileged(
- new java.security.PrivilegedAction() {
- public Object run() {
- try {
- File f = new File(fileName);
- return Boolean.valueOf(f.exists());
- }
- catch (Exception e) {
- return false;
- }
- }
- });
- return exists.booleanValue();
- }
- private void findFontConfigFile() {
- foundOsSpecificFile = true; // default assumption.
- String javaHome = System.getProperty("java.home");
- if (javaHome == null) {
- throw new Error("java.home property not set");
- }
- javaLib = javaHome + File.separator + "lib";
- String userConfigFile = System.getProperty("sun.awt.fontconfig");
- if (userConfigFile != null) {
- fontConfigFile = new File(userConfigFile);
- } else {
- fontConfigFile = findFontConfigFile(javaLib);
- }
- }
- private void readFontConfigFile(File f) {
- /* This is invoked here as readFontConfigFile is only invoked
- * once per VM, and always in a privileged context, thus the
- * directory containing installed fall back fonts is accessed
- * from this context
- */
- getInstalledFallbackFonts(javaLib);
- if (f != null) {
- try {
- FileInputStream in = new FileInputStream(f.getPath());
- if (isProperties) {
- loadProperties(in);
- } else {
- loadBinary(in);
- }
- in.close();
- if (FontUtilities.debugFonts()) {
- logger.config("Read logical font configuration from " + f);
- }
- } catch (IOException e) {
- if (FontUtilities.debugFonts()) {
- logger.config("Failed to read logical font configuration from " + f);
- }
- }
- }
- String version = getVersion();
- if (!"1".equals(version) && FontUtilities.debugFonts()) {
- logger.config("Unsupported fontconfig version: " + version);
- }
- }
- protected void getInstalledFallbackFonts(String javaLib) {
- String fallbackDirName = javaLib + File.separator +
- "fonts" + File.separator + "fallback";
- File fallbackDir = new File(fallbackDirName);
- if (fallbackDir.exists() && fallbackDir.isDirectory()) {
- String[] ttfs = fallbackDir.list(fontManager.getTrueTypeFilter());
- String[] t1s = fallbackDir.list(fontManager.getType1Filter());
- int numTTFs = (ttfs == null) ? 0 : ttfs.length;
- int numT1s = (t1s == null) ? 0 : t1s.length;
- int len = numTTFs + numT1s;
- if (numTTFs + numT1s == 0) {
- return;
- }
- installedFallbackFontFiles = new String[len];
- for (int i=0; i<numTTFs; i++) {
- installedFallbackFontFiles[i] =
- fallbackDir + File.separator + ttfs[i];
- }
- for (int i=0; i<numT1s; i++) {
- installedFallbackFontFiles[i+numTTFs] =
- fallbackDir + File.separator + t1s[i];
- }
- fontManager.registerFontsInDir(fallbackDirName);
- }
- }
- private File findImpl(String fname) {
- File f = new File(fname + ".properties");
- if (f.canRead()) {
- isProperties = true;
- return f;
- }
- f = new File(fname + ".bfc");
- if (f.canRead()) {
- isProperties = false;
- return f;
- }
- return null;
- }
- private File findFontConfigFile(String javaLib) {
- String baseName = javaLib + File.separator + "fontconfig";
- File configFile;
- String osMajorVersion = null;
- if (osVersion != null && osName != null) {
- configFile = findImpl(baseName + "." + osName + "." + osVersion);
- if (configFile != null) {
- return configFile;
- }
- int decimalPointIndex = osVersion.indexOf(".");
- if (decimalPointIndex != -1) {
- osMajorVersion = osVersion.substring(0, osVersion.indexOf("."));
- configFile = findImpl(baseName + "." + osName + "." + osMajorVersion);
- if (configFile != null) {
- return configFile;
- }
- }
- }
- if (osName != null) {
- configFile = findImpl(baseName + "." + osName);
- if (configFile != null) {
- return configFile;
- }
- }
- if (osVersion != null) {
- configFile = findImpl(baseName + "." + osVersion);
- if (configFile != null) {
- return configFile;
- }
- if (osMajorVersion != null) {
- configFile = findImpl(baseName + "." + osMajorVersion);
- if (configFile != null) {
- return configFile;
- }
- }
- }
- foundOsSpecificFile = false;
- configFile = findImpl(baseName);
- if (configFile != null) {
- return configFile;
- }
- return null;
- }
- /* Initialize the internal data tables from binary format font
- * configuration file.
- */
- public static void loadBinary(InputStream inStream) throws IOException {
- DataInputStream in = new DataInputStream(inStream);
- head = readShortTable(in, HEAD_LENGTH);
- int[] tableSizes = new int[INDEX_TABLEEND];
- for (int i = 0; i < INDEX_TABLEEND; i++) {
- tableSizes[i] = head[i + 1] - head[i];
- }
- table_scriptIDs = readShortTable(in, tableSizes[INDEX_scriptIDs]);
- table_scriptFonts = readShortTable(in, tableSizes[INDEX_scriptFonts]);
- table_elcIDs = readShortTable(in, tableSizes[INDEX_elcIDs]);
- table_sequences = readShortTable(in, tableSizes[INDEX_sequences]);
- table_fontfileNameIDs = readShortTable(in, tableSizes[INDEX_fontfileNameIDs]);
- table_componentFontNameIDs = readShortTable(in, tableSizes[INDEX_componentFontNameIDs]);
- table_filenames = readShortTable(in, tableSizes[INDEX_filenames]);
- table_awtfontpaths = readShortTable(in, tableSizes[INDEX_awtfontpaths]);
- table_exclusions = readShortTable(in, tableSizes[INDEX_exclusions]);
- table_proportionals = readShortTable(in, tableSizes[INDEX_proportionals]);
- table_scriptFontsMotif = readShortTable(in, tableSizes[INDEX_scriptFontsMotif]);
- table_alphabeticSuffix = readShortTable(in, tableSizes[INDEX_alphabeticSuffix]);
- table_stringIDs = readShortTable(in, tableSizes[INDEX_stringIDs]);
- //StringTable cache
- stringCache = new String[table_stringIDs.length + 1];
- int len = tableSizes[INDEX_stringTable];
- byte[] bb = new byte[len * 2];
- table_stringTable = new char[len];
- in.read(bb);
- int i = 0, j = 0;
- while (i < len) {
- table_stringTable[i++] = (char)(bb[j++] << 8 | (bb[j++] & 0xff));
- }
- if (verbose) {
- dump();
- }
- }
- /* Generate a binary format font configuration from internal data
- * tables.
- */
- public static void saveBinary(OutputStream out) throws IOException {
- sanityCheck();
- DataOutputStream dataOut = new DataOutputStream(out);
- writeShortTable(dataOut, head);
- writeShortTable(dataOut, table_scriptIDs);
- writeShortTable(dataOut, table_scriptFonts);
- writeShortTable(dataOut, table_elcIDs);
- writeShortTable(dataOut, table_sequences);
- writeShortTable(dataOut, table_fontfileNameIDs);
- writeShortTable(dataOut, table_componentFontNameIDs);
- writeShortTable(dataOut, table_filenames);
- writeShortTable(dataOut, table_awtfontpaths);
- writeShortTable(dataOut, table_exclusions);
- writeShortTable(dataOut, table_proportionals);
- writeShortTable(dataOut, table_scriptFontsMotif);
- writeShortTable(dataOut, table_alphabeticSuffix);
- writeShortTable(dataOut, table_stringIDs);
- //stringTable
- dataOut.writeChars(new String(table_stringTable));
- out.close();
- if (verbose) {
- dump();
- }
- }
- //private static boolean loadingProperties;
- private static short stringIDNum;
- private static short[] stringIDs;
- private static StringBuilder stringTable;
- public static void loadProperties(InputStream in) throws IOException {
- //loadingProperties = true;
- //StringID starts from "1", "0" is reserved for "not defined"
- stringIDNum = 1;
- stringIDs = new short[1000];
- stringTable = new StringBuilder(4096);
- if (verbose && logger == null) {
- logger = PlatformLogger.getLogger("sun.awt.FontConfiguration");
- }
- new PropertiesHandler().load(in);
- //loadingProperties = false;
- stringIDs = null;
- stringTable = null;
- }
- /////////////////////////////////////////////////////////////////////
- // methods for initializing the FontConfig //
- /////////////////////////////////////////////////////////////////////
- /**
- * set initLocale, initEncoding and initELC for this FontConfig object
- * currently we just simply use the startup locale and encoding
- */
- private void initFontConfig() {
- initLocale = startupLocale;
- initEncoding = encoding;
- if (preferLocaleFonts && !willReorderForStartupLocale()) {
- preferLocaleFonts = false;
- }
- initELC = getInitELC();
- initAllComponentFonts();
- }
- //"ELC" stands for "Encoding.Language.Country". This method returns
- //the ID of the matched elc setting of "initLocale" in elcIDs table.
- //If no match is found, it returns the default ID, which is
- //"NULL.NULL.NULL" in elcIDs table.
- private short getInitELC() {
- if (initELC != -1) {
- return initELC;
- }
- HashMap <String, Integer> elcIDs = new HashMap<String, Integer>();
- for (int i = 0; i < table_elcIDs.length; i++) {
- elcIDs.put(getString(table_elcIDs[i]), i);
- }
- String language = initLocale.getLanguage();
- String country = initLocale.getCountry();
- String elc;
- if (elcIDs.containsKey(elc=initEncoding + "." + language + "." + country)
- || elcIDs.containsKey(elc=initEncoding + "." + language)
- || elcIDs.containsKey(elc=initEncoding)) {
- initELC = elcIDs.get(elc).shortValue();
- } else {
- initELC = elcIDs.get("NULL.NULL.NULL").shortValue();
- }
- int i = 0;
- while (i < table_alphabeticSuffix.length) {
- if (initELC == table_alphabeticSuffix[i]) {
- alphabeticSuffix = getString(table_alphabeticSuffix[i + 1]);
- return initELC;
- }
- i += 2;
- }
- return initELC;
- }
- public static boolean verbose;
- private short initELC = -1;
- private Locale initLocale;
- private String initEncoding;
- private String alphabeticSuffix;
- private short[][][] compFontNameIDs = new short[NUM_FONTS][NUM_STYLES][];
- private int[][][] compExclusions = new int[NUM_FONTS][][];
- private int[] compCoreNum = new int[NUM_FONTS];
- private Set<Short> coreFontNameIDs = new HashSet<Short>();
- private Set<Short> fallbackFontNameIDs = new HashSet<Short>();
- private void initAllComponentFonts() {
- short[] fallbackScripts = getFallbackScripts();
- for (int fontIndex = 0; fontIndex < NUM_FONTS; fontIndex++) {
- short[] coreScripts = getCoreScripts(fontIndex);
- compCoreNum[fontIndex] = coreScripts.length;
- /*
- System.out.println("coreScriptID=" + table_sequences[initELC * 5 + fontIndex]);
- for (int i = 0; i < coreScripts.length; i++) {
- System.out.println(" " + i + " :" + getString(table_scriptIDs[coreScripts[i]]));
- }
- */
- //init exclusionRanges
- int[][] exclusions = new int[coreScripts.length][];
- for (int i = 0; i < coreScripts.length; i++) {
- exclusions[i] = getExclusionRanges(coreScripts[i]);
- }
- compExclusions[fontIndex] = exclusions;
- //init componentFontNames
- for (int styleIndex = 0; styleIndex < NUM_STYLES; styleIndex++) {
- int index;
- short[] nameIDs = new short[coreScripts.length + fallbackScripts.length];
- //core
- for (index = 0; index < coreScripts.length; index++) {
- nameIDs[index] = getComponentFontID(coreScripts[index],
- fontIndex, styleIndex);
- if (preferLocaleFonts && localeMap != null &&
- fontManager.usingAlternateFontforJALocales()) {
- nameIDs[index] = remapLocaleMap(fontIndex, styleIndex,
- coreScripts[index], nameIDs[index]);
- }
- if (preferPropFonts) {
- nameIDs[index] = remapProportional(fontIndex, nameIDs[index]);
- }
- //System.out.println("nameid=" + nameIDs[index]);
- coreFontNameIDs.add(nameIDs[index]);
- }
- //fallback
- for (int i = 0; i < fallbackScripts.length; i++) {
- short id = getComponentFontID(fallbackScripts[i],
- fontIndex, styleIndex);
- if (preferLocaleFonts && localeMap != null &&
- fontManager.usingAlternateFontforJALocales()) {
- id = remapLocaleMap(fontIndex, styleIndex, fallbackScripts[i], id);
- }
- if (preferPropFonts) {
- id = remapProportional(fontIndex, id);
- }
- if (contains(nameIDs, id, index)) {
- continue;
- }
- /*
- System.out.println("fontIndex=" + fontIndex + ", styleIndex=" + styleIndex
- + ", fbIndex=" + i + ",fbS=" + fallbackScripts[i] + ", id=" + id);
- */
- fallbackFontNameIDs.add(id);
- nameIDs[index++] = id;
- }
- if (index < nameIDs.length) {
- short[] newNameIDs = new short[index];
- System.arraycopy(nameIDs, 0, newNameIDs, 0, index);
- nameIDs = newNameIDs;
- }
- compFontNameIDs[fontIndex][styleIndex] = nameIDs;
- }
- }
- }
- private short remapLocaleMap(int fontIndex, int styleIndex, short scriptID, short fontID) {
- String scriptName = getString(table_scriptIDs[scriptID]);
- String value = (String)localeMap.get(scriptName);
- if (value == null) {
- String fontName = fontNames[fontIndex];
- String styleName = styleNames[styleIndex];
- value = (String)localeMap.get(fontName + "." + styleName + "." + scriptName);
- }
- if (value == null) {
- return fontID;
- }
- for (int i = 0; i < table_componentFontNameIDs.length; i++) {
- String name = getString(table_componentFontNameIDs[i]);
- if (value.equalsIgnoreCase(name)) {
- fontID = (short)i;
- break;
- }
- }
- return fontID;
- }
- public static boolean hasMonoToPropMap() {
- return table_proportionals != null && table_proportionals.length != 0;
- }
- private short remapProportional(int fontIndex, short id) {
- if (preferPropFonts &&
- table_proportionals.length != 0 &&
- fontIndex != 2 && //"monospaced"
- fontIndex != 4) { //"dialoginput"
- int i = 0;
- while (i < table_proportionals.length) {
- if (table_proportionals[i] == id) {
- return table_proportionals[i + 1];
- }
- i += 2;
- }
- }
- return id;
- }
- /////////////////////////////////////////////////////////////////////
- // Methods for handling font and style names //
- /////////////////////////////////////////////////////////////////////
- protected static final int NUM_FONTS = 5;
- protected static final int NUM_STYLES = 4;
- protected static final String[] fontNames
- = {"serif", "sansserif", "monospaced", "dialog", "dialoginput"};
- protected static final String[] publicFontNames
- = {Font.SERIF, Font.SANS_SERIF, Font.MONOSPACED, Font.DIALOG,
- Font.DIALOG_INPUT};
- protected static final String[] styleNames
- = {"plain", "bold", "italic", "bolditalic"};
- /**
- * Checks whether the given font family name is a valid logical font name.
- * The check is case insensitive.
- */
- public static boolean isLogicalFontFamilyName(String fontName) {
- return isLogicalFontFamilyNameLC(fontName.toLowerCase(Locale.ENGLISH));
- }
- /**
- * Checks whether the given font family name is a valid logical font name.
- * The check is case sensitive.
- */
- public static boolean isLogicalFontFamilyNameLC(String fontName) {
- for (int i = 0; i < fontNames.length; i++) {
- if (fontName.equals(fontNames[i])) {
- return true;
- }
- }
- return false;
- }
- /**
- * Checks whether the given style name is a valid logical font style name.
- */
- private static boolean isLogicalFontStyleName(String styleName) {
- for (int i = 0; i < styleNames.length; i++) {
- if (styleName.equals(styleNames[i])) {
- return true;
- }
- }
- return false;
- }
- /**
- * Checks whether the given font face name is a valid logical font name.
- * The check is case insensitive.
- */
- public static boolean isLogicalFontFaceName(String fontName) {
- return isLogicalFontFaceNameLC(fontName.toLowerCase(Locale.ENGLISH));
- }
- /**
- * Checks whether the given font face name is a valid logical font name.
- * The check is case sensitive.
- */
- public static boolean isLogicalFontFaceNameLC(String fontName) {
- int period = fontName.indexOf('.');
- if (period >= 0) {
- String familyName = fontName.substring(0, period);
- String styleName = fontName.substring(period + 1);
- return isLogicalFontFamilyName(familyName) &&
- isLogicalFontStyleName(styleName);
- } else {
- return isLogicalFontFamilyName(fontName);
- }
- }
- protected static int getFontIndex(String fontName) {
- return getArrayIndex(fontNames, fontName);
- }
- protected static int getStyleIndex(String styleName) {
- return getArrayIndex(styleNames, styleName);
- }
- private static int getArrayIndex(String[] names, String name) {
- for (int i = 0; i < names.length; i++) {
- if (name.equals(names[i])) {
- return i;
- }
- }
- assert false;
- return 0;
- }
- protected static int getStyleIndex(int style) {
- switch (style) {
- case Font.PLAIN:
- return 0;
- case Font.BOLD:
- return 1;
- case Font.ITALIC:
- return 2;
- case Font.BOLD | Font.ITALIC:
- return 3;
- default:
- return 0;
- }
- }
- protected static String getFontName(int fontIndex) {
- return fontNames[fontIndex];
- }
- protected static String getStyleName(int styleIndex) {
- return styleNames[styleIndex];
- }
- /**
- * Returns the font face name for the given logical font
- * family name and style.
- * The style argument is interpreted as in java.awt.Font.Font.
- */
- public static String getLogicalFontFaceName(String familyName, int style) {
- assert isLogicalFontFamilyName(familyName);
- return familyName.toLowerCase(Locale.ENGLISH) + "." + getStyleString(style);
- }
- /**
- * Returns the string typically used in properties files
- * for the given style.
- * The style argument is interpreted as in java.awt.Font.Font.
- */
- public static String getStyleString(int style) {
- return getStyleName(getStyleIndex(style));
- }
- /**
- * Returns a fallback name for the given font name. For a few known
- * font names, matching logical font names are returned. For all
- * other font names, defaultFallback is returned.
- * defaultFallback differs between AWT and 2D.
- */
- public abstract String getFallbackFamilyName(String fontName, String defaultFallback);
- /**
- * Returns the 1.1 equivalent for some old 1.0 font family names for
- * which we need to maintain compatibility in some configurations.
- * Returns null for other font names.
- */
- protected String getCompatibilityFamilyName(String fontName) {
- fontName = fontName.toLowerCase(Locale.ENGLISH);
- if (fontName.equals("timesroman")) {
- return "serif";
- } else if (fontName.equals("helvetica")) {
- return "sansserif";
- } else if (fontName.equals("courier")) {
- return "monospaced";
- }
- return null;
- }
- protected static String[] installedFallbackFontFiles = null;
- /**
- * Maps a file name given in the font configuration file
- * to a format appropriate for the platform.
- */
- protected String mapFileName(String fileName) {
- return fileName;
- }
- //////////////////////////////////////////////////////////////////////
- // reordering //
- //////////////////////////////////////////////////////////////////////
- /* Mappings from file encoding to font config name for font supporting
- * the corresponding language. This is filled in by initReorderMap()
- */
- protected HashMap reorderMap = null;
- /* Platform-specific mappings */
- protected abstract void initReorderMap();
- /* Move item at index "src" to "dst", shuffling all values in
- * between down
- */
- private void shuffle(String[] seq, int src, int dst) {
- if (dst >= src) {
- return;
- }
- String tmp = seq[src];
- for (int i=src; i>dst; i--) {
- seq[i] = seq[i-1];
- }
- seq[dst] = tmp;
- }
- /* Called to determine if there's a re-order sequence for this locale/
- * encoding. If there's none then the caller can "bail" and avoid
- * unnecessary work
- */
- public static boolean willReorderForStartupLocale() {
- return getReorderSequence() != null;
- }
- private static Object getReorderSequence() {
- if (fontConfig.reorderMap == null) {
- fontConfig.initReorderMap();
- }
- HashMap reorderMap = fontConfig.reorderMap;
- /* Find the most specific mapping */
- String language = startupLocale.getLanguage();
- String country = startupLocale.getCountry();
- Object val = reorderMap.get(encoding + "." + language + "." + country);
- if (val == null) {
- val = reorderMap.get(encoding + "." + language);
- }
- if (val == null) {
- val = reorderMap.get(encoding);
- }
- return val;
- }
- /* This method reorders the sequence such that the matches for the
- * file encoding are moved ahead of other elements.
- * If an encoding uses more than one font, they are all moved up.
- */
- private void reorderSequenceForLocale(String[] seq) {
- Object val = getReorderSequence();
- if (val instanceof String) {
- for (int i=0; i< seq.length; i++) {
- if (seq[i].equals(val)) {
- shuffle(seq, i, 0);
- return;
- }
- }
- } else if (val instanceof String[]) {
- String[] fontLangs = (String[])val;
- for (int l=0; l<fontLangs.length;l++) {
- for (int i=0; i<seq.length;i++) {
- if (seq[i].equals(fontLangs[l])) {
- shuffle(seq, i, l);
- }
- }
- }
- }
- }
- private static Vector splitSequence(String sequence) {
- //String.split would be more convenient, but incurs big performance penalty
- Vector parts = new Vector();
- int start = 0;
- int end;
- while ((end = sequence.indexOf(',', start)) >= 0) {
- parts.add(sequence.substring(start, end));
- start = end + 1;
- }
- if (sequence.length() > start) {
- parts.add(sequence.substring(start, sequence.length()));
- }
- return parts;
- }
- protected String[] split(String sequence) {
- Vector v = splitSequence(sequence);
- return (String[])v.toArray(new String[0]);
- }
- ////////////////////////////////////////////////////////////////////////
- // Methods for extracting information from the fontconfig data for AWT//
- ////////////////////////////////////////////////////////////////////////
- private Hashtable charsetRegistry = new Hashtable(5);
- /**
- * Returns FontDescriptors describing the physical fonts used for the
- * given logical font name and style. The font name is interpreted
- * in a case insensitive way.
- * The style argument is interpreted as in java.awt.Font.Font.
- */
- public FontDescriptor[] getFontDescriptors(String fontName, int style) {
- assert isLogicalFontFamilyName(fontName);
- fontName = fontName.toLowerCase(Locale.ENGLISH);
- int fontIndex = getFontIndex(fontName);
- int styleIndex = getStyleIndex(style);
- return getFontDescriptors(fontIndex, styleIndex);
- }
- private FontDescriptor[][][] fontDescriptors =
- new FontDescriptor[NUM_FONTS][NUM_STYLES][];
- private FontDescriptor[] getFontDescriptors(int fontIndex, int styleIndex) {
- FontDescriptor[] descriptors = fontDescriptors[fontIndex][styleIndex];
- if (descriptors == null) {
- descriptors = buildFontDescriptors(fontIndex, styleIndex);
- fontDescriptors[fontIndex][styleIndex] = descriptors;
- }
- return descriptors;
- }
- private FontDescriptor[] buildFontDescriptors(int fontIndex, int styleIndex) {
- String fontName = fontNames[fontIndex];
- String styleName = styleNames[styleIndex];
- short[] scriptIDs = getCoreScripts(fontIndex);
- short[] nameIDs = compFontNameIDs[fontIndex][styleIndex];
- String[] sequence = new String[scriptIDs.length];
- String[] names = new String[scriptIDs.length];
- for (int i = 0; i < sequence.length; i++) {
- names[i] = getComponentFontName(nameIDs[i]);
- sequence[i] = getScriptName(scriptIDs[i]);
- if (alphabeticSuffix != null && "alphabetic".equals(sequence[i])) {
- sequence[i] = sequence[i] + "/" + alphabeticSuffix;
- }
- }
- int[][] fontExclusionRanges = compExclusions[fontIndex];
- FontDescriptor[] descriptors = new FontDescriptor[names.length];
- for (int i = 0; i < names.length; i++) {
- String awtFontName;
- String encoding;
- awtFontName = makeAWTFontName(names[i], sequence[i]);
- // look up character encoding
- encoding = getEncoding(names[i], sequence[i]);
- if (encoding == null) {
- encoding = "default";
- }
- CharsetEncoder enc
- = getFontCharsetEncoder(encoding.trim(), awtFontName);
- // we already have the exclusion ranges
- int[] exclusionRanges = fontExclusionRanges[i];
- // create descriptor
- descriptors[i] = new FontDescriptor(awtFontName, enc, exclusionRanges);
- }
- return descriptors;
- }
- /**
- * Returns the AWT font name for the given platform font name and
- * character subset.
- */
- protected String makeAWTFontName(String platformFontName,
- String characterSubsetName) {
- return platformFontName;
- }
- /**
- * Returns the java.io name of the platform character encoding for the
- * given AWT font name and character subset. May return "default"
- * to indicate that getDefaultFontCharset should be called to obtain
- * a charset encoder.
- */
- protected abstract String getEncoding(String awtFontName,
- String characterSubsetName);
- private CharsetEncoder getFontCharsetEncoder(final String charsetName,
- String fontName) {
- Charset fc = null;
- if (charsetName.equals("default")) {
- fc = (Charset) charsetRegistry.get(fontName);
- } else {
- fc = (Charset) charsetRegistry.get(charsetName);
- }
- if (fc != null) {
- return fc.newEncoder();
- }
- if (!charsetName.startsWith("sun.awt.") && !charsetName.equals("default")) {
- fc = Charset.forName(charsetName);
- } else {
- Class fcc = (Class) AccessController.doPrivileged(new PrivilegedAction() {
- public Object run() {
- try {
- return Class.forName(charsetName, true,
- ClassLoader.getSystemClassLoader());
- } catch (ClassNotFoundException e) {
- }
- return null;
- }
- });
- if (fcc != null) {
- try {
- fc = (Charset) fcc.newInstance();
- } catch (Exception e) {
- }
- }
- }
- if (fc == null) {
- fc = getDefaultFontCharset(fontName);
- }
- if (charsetName.equals("default")){
- charsetRegistry.put(fontName, fc);
- } else {
- charsetRegistry.put(charsetName, fc);
- }
- return fc.newEncoder();
- }
- protected abstract Charset getDefaultFontCharset(
- String fontName);
- /* This retrieves the platform font directories (path) calculated
- * by setAWTFontPathSequence(String[]). The default implementation
- * returns null, its expected that X11 platforms may return
- * non-null.
- */
- public HashSet<String> getAWTFontPathSet() {
- return null;
- }
- ////////////////////////////////////////////////////////////////////////
- // methods for extracting information from the fontconfig data for 2D //
- ////////////////////////////////////////////////////////////////////////
- /**
- * Returns an array of composite font descriptors for all logical font
- * faces.
- * If the font configuration file doesn't specify Lucida Sans Regular
- * or the given fallback font as component fonts, they are added here.
- */
- public CompositeFontDescriptor[] get2DCompositeFontInfo() {
- CompositeFontDescriptor[] result =
- new CompositeFontDescriptor[NUM_FONTS * NUM_STYLES];
- String defaultFontFile = fontManager.getDefaultFontFile();
- String defaultFontFaceName = fontManager.getDefaultFontFaceName();
- for (int fontIndex = 0; fontIndex < NUM_FONTS; fontIndex++) {
- String fontName = publicFontNames[fontIndex];
- // determine exclusion ranges for font
- // AWT uses separate exclusion range array per component font.
- // 2D packs all range boundaries into one array.
- // Both use separate entries for lower and upper boundary.
- int[][] exclusions = compExclusions[fontIndex];
- int numExclusionRanges = 0;
- for (int i = 0; i < exclusions.length; i++) {
- numExclusionRanges += exclusions[i].length;
- }
- int[] exclusionRanges = new int[numExclusionRanges];
- int[] exclusionRangeLimits = new int[exclusions.length];
- int exclusionRangeIndex = 0;
- int exclusionRangeLimitIndex = 0;
- for (int i = 0; i < exclusions.length; i++) {
- int[] componentRanges = exclusions[i];
- for (int j = 0; j < componentRanges.length; ) {
- int value = componentRanges[j];
- exclusionRanges[exclusionRangeIndex++] = componentRanges[j++];
- exclusionRanges[exclusionRangeIndex++] = componentRanges[j++];
- }
- exclusionRangeLimits[i] = exclusionRangeIndex;
- }
- // other info is per style
- for (int styleIndex = 0; styleIndex < NUM_STYLES; styleIndex++) {
- int maxComponentFontCount = compFontNameIDs[fontIndex][styleIndex].length;
- boolean sawDefaultFontFile = false;
- // fall back fonts listed in the lib/fonts/fallback directory
- if (installedFallbackFontFiles != null) {
- maxComponentFontCount += installedFallbackFontFiles.length;
- }
- String faceName = fontName + "." + styleNames[styleIndex];
- // determine face names and file names of component fonts
- String[] componentFaceNames = new String[maxComponentFontCount];
- String[] componentFileNames = new String[maxComponentFontCount];
- int index;
- for (index = 0; index < compFontNameIDs[fontIndex][styleIndex].length; index++) {
- short fontNameID = compFontNameIDs[fontIndex][styleIndex][index];
- short fileNameID = getComponentFileID(fontNameID);
- componentFaceNames[index] = getFaceNameFromComponentFontName(getComponentFontName(fontNameID));
- componentFileNames[index] = mapFileName(getComponentFileName(fileNameID));
- if (componentFileNames[index] == null ||
- needToSearchForFile(componentFileNames[index])) {
- componentFileNames[index] = getFileNameFromComponentFontName(getComponentFontName(fontNameID));
- }
- if (!sawDefaultFontFile &&
- defaultFontFile.equals(componentFileNames[index])) {
- sawDefaultFontFile = true;
- }
- /*
- System.out.println(publicFontNames[fontIndex] + "." + styleNames[styleIndex] + "."
- + getString(table_scriptIDs[coreScripts[index]]) + "=" + componentFileNames[index]);
- */
- }
- //"Lucida Sans Regular" is not in the list, we add it here
- if (!sawDefaultFontFile) {
- int len = 0;
- if (installedFallbackFontFiles != null) {
- len = installedFallbackFontFiles.length;
- }
- if (index + len == maxComponentFontCount) {
- String[] newComponentFaceNames = new String[maxComponentFontCount + 1];
- System.arraycopy(componentFaceNames, 0, newComponentFaceNames, 0, index);
- componentFaceNames = newComponentFaceNames;
- String[] newComponentFileNames = new String[maxComponentFontCount + 1];
- System.arraycopy(componentFileNames, 0, newComponentFileNames, 0, index);
- componentFileNames = newComponentFileNames;
- }
- componentFaceNames[index] = defaultFontFaceName;
- componentFileNames[index] = defaultFontFile;
- index++;
- }
- if (installedFallbackFontFiles != null) {
- for (int ifb=0; ifb<installedFallbackFontFiles.length; ifb++) {
- componentFaceNames[index] = null;
- componentFileNames[index] = installedFallbackFontFiles[ifb];
- index++;
- }
- }
- if (index < maxComponentFontCount) {
- String[] newComponentFaceNames = new String[index];
- System.arraycopy(componentFaceNames, 0, newComponentFaceNames, 0, index);
- componentFaceNames = newComponentFaceNames;
- String[] newComponentFileNames = new String[index];
- System.arraycopy(componentFileNames, 0, newComponentFileNames, 0, index);
- componentFileNames = newComponentFileNames;
- }
- // exclusion range limit array length must match component face name
- // array length - native code relies on this
- int[] clippedExclusionRangeLimits = exclusionRangeLimits;
- if (index != clippedExclusionRangeLimits.length) {
- int len = exclusionRangeLimits.length;
- clippedExclusionRangeLimits = new int[index];
- System.arraycopy(exclusionRangeLimits, 0, clippedExclusionRangeLimits, 0, len);
- //padding for various fallback fonts
- for (int i = len; i < index; i++) {
- clippedExclusionRangeLimits[i] = exclusionRanges.length;
- }
- }
- /*
- System.out.println(faceName + ":");
- for (int i = 0; i < componentFileNames.length; i++) {
- System.out.println(" " + componentFaceNames[i]
- + " -> " + componentFileNames[i]);
- }
- */
- result[fontIndex * NUM_STYLES + styleIndex]
- = new CompositeFontDescriptor(
- faceName,
- compCoreNum[fontIndex],
- componentFaceNames,
- componentFileNames,
- exclusionRanges,
- clippedExclusionRangeLimits);
- }
- }
- return result;
- }
- protected abstract String getFaceNameFromComponentFontName(String componentFontName);
- protected abstract String getFileNameFromComponentFontName(String componentFontName);
- /*
- public class 2dFont {
- public String platformName;
- public String fontfileName;
- }
- private 2dFont [] componentFonts = null;
- */
- /* Used on Linux to test if a file referenced in a font configuration
- * file exists in the location that is expected. If it does, no need
- * to search for it. If it doesn't then unless its a fallback font,
- * return that expensive code should be invoked to search for the font.
- */
- HashMap<String, Boolean> existsMap;
- public boolean needToSearchForFile(String fileName) {
- if (!FontUtilities.isLinux) {
- return false;
- } else if (existsMap == null) {
- existsMap = new HashMap<String, Boolean>();
- }
- Boolean exists = existsMap.get(fileName);
- if (exists == null) {
- /* call getNumberCoreFonts() to ensure these are initialised, and
- * if this file isn't for a core component, ie, is a for a fallback
- * font which very typically isn't available, then can't afford
- * to take the start-up penalty to search for it.
- */
- getNumberCoreFonts();
- if (!coreFontFileNames.contains(fileName)) {
- exists = Boolean.TRUE;
- } else {
- exists = Boolean.valueOf((new File(fileName)).exists());
- existsMap.put(fileName, exists);
- if (FontUtilities.debugFonts() &&
- exists == Boolean.FALSE) {
- logger.warning("Couldn't locate font file " + fileName);
- }
- }
- }
- return exists == Boolean.FALSE;
- }
- private int numCoreFonts = -1;
- private String[] componentFonts = null;
- HashMap <String, String> filenamesMap = new HashMap<String, String>();
- HashSet <String> coreFontFileNames = new HashSet<String>();
- /* Return the number of core fonts. Note this isn't thread safe but
- * a calling thread can call this and getPlatformFontNames() in either
- * order.
- */
- public int getNumberCoreFonts() {
- if (numCoreFonts == -1) {
- numCoreFonts = coreFontNameIDs.size();
- Short[] emptyShortArray = new Short[0];
- Short[] core = coreFontNameIDs.toArray(emptyShortArray);
- Short[] fallback = fallbackFontNameIDs.toArray(emptyShortArray);
- int numFallbackFonts = 0;
- int i;
- for (i = 0; i < fallback.length; i++) {
- if (coreFontNameIDs.contains(fallback[i])) {
- fallback[i] = null;
- continue;
- }
- numFallbackFonts++;
- }
- componentFonts = new String[numCoreFonts + numFallbackFonts];
- String filename = null;
- for (i = 0; i < core.length; i++) {
- short fontid = core[i];
- short fileid = getComponentFileID(fontid);
- componentFonts[i] = getComponentFontName(fontid);
- String compFileName = getComponentFileName(fileid);
- if (compFileName != null) {
- coreFontFileNames.add(compFileName);
- }
- filenamesMap.put(componentFonts[i], mapFileName(compFileName));
- }
- for (int j = 0; j < fallback.length; j++) {
- if (fallback[j] != null) {
- short fontid = fallback[j];
- short fileid = getComponentFileID(fontid);
- componentFonts[i] = getComponentFontName(fontid);
- filenamesMap.put(componentFonts[i],
- mapFileName(getComponentFileName(fileid)));
- i++;
- }
- }
- }
- return numCoreFonts;
- }
- /* Return all platform font names used by this font configuration.
- * The first getNumberCoreFonts() entries are guaranteed to be the
- * core fonts - ie no fall back only fonts.
- */
- public String[] getPlatformFontNames() {
- if (numCoreFonts == -1) {
- getNumberCoreFonts();
- }
- return componentFonts;
- }
- /**
- * Returns a file name for the physical font represented by this platform font name,
- * if the font configuration has such information available, or null if the
- * information is unavailable. The file name returned is just a hint; a null return
- * value doesn't necessarily mean that the font is unavailable, nor does a non-null
- * return value guarantee that the file exists and contains the physical font.
- * The file name can be an absolute or a relative path name.
- */
- public String getFileNameFromPlatformName(String platformName) {
- // get2DCompositeFontInfo
- // -> getFileNameFromComponentfontName() (W/M)
- // -> getFileNameFromPlatformName()
- // it's a waste of time on Win32, but I have to give X11 a chance to
- // call getFileNameFromXLFD()
- …
Large files files are truncated, but you can click here to view the full file