提交 84c7e7ae 编写于 作者: R rkennke

6869705: Missing files of CR6795908, FontManager refactoring

Reviewed-by: prr, igor
上级 e43dcf4d
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.font;
import java.awt.Font;
public abstract class FontAccess {
private static FontAccess access;
public static synchronized void setFontAccess(FontAccess acc) {
if (access != null) {
throw new InternalError("Attempt to set FontAccessor twice");
}
access = acc;
}
public static synchronized FontAccess getFontAccess() {
return access;
}
public abstract Font2D getFont2D(Font f);
public abstract void setFont2D(Font f, Font2DHandle h);
public abstract void setCreatedFont(Font f);
public abstract boolean isCreatedFont(Font f);
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.font;
import java.awt.AWTError;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.security.action.GetPropertyAction;
/**
* Factory class used to retrieve a valid FontManager instance for the current
* platform.
*
* A default implementation is given for Linux, Solaris and Windows.
* You can alter the behaviour of the {@link #getInstance()} method by setting
* the {@code sun.font.fontmanager} property. For example:
* {@code sun.font.fontmanager=sun.awt.X11FontManager}
*/
public final class FontManagerFactory {
/** Our singleton instance. */
private static FontManager instance = null;
private static final String DEFAULT_CLASS;
static {
if (FontUtilities.isWindows)
DEFAULT_CLASS = "sun.awt.Win32FontManager";
else
DEFAULT_CLASS = "sun.awt.X11FontManager";
}
/**
* Get a valid FontManager implementation for the current platform.
*
* @return a valid FontManager instance for the current platform
*/
public static synchronized FontManager getInstance() {
if (instance != null) {
return instance;
}
String fmClassName = AccessController.doPrivileged(
new GetPropertyAction("sun.font.fontmanager",
DEFAULT_CLASS));
try {
@SuppressWarnings("unchecked")
ClassLoader cl = (ClassLoader)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return ClassLoader.getSystemClassLoader();
}
});
@SuppressWarnings("unchecked")
Class fmClass = Class.forName(fmClassName, true, cl);
instance = (FontManager) fmClass.newInstance();
} catch (ClassNotFoundException ex) {
InternalError err = new InternalError();
err.initCause(ex);
throw err;
} catch (InstantiationException ex) {
InternalError err = new InternalError();
err.initCause(ex);
throw err;
} catch (IllegalAccessException ex) {
InternalError err = new InternalError();
err.initCause(ex);
throw err;
}
return instance;
}
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.font;
import java.awt.Font;
import java.util.Locale;
import java.util.TreeMap;
/**
* This is an extension of the {@link FontManager} interface which has to
* be implemented on systems that want to use SunGraphicsEnvironment. It
* adds a couple of methods that are only required by SGE. Graphics
* implementations that use their own GraphicsEnvironment are not required
* to implement this and can use plain FontManager instead.
*/
public interface FontManagerForSGE extends FontManager {
/**
* Return an array of created Fonts, or null, if no fonts were created yet.
*/
public Font[] getCreatedFonts();
/**
* Similar to getCreatedFonts, but returns a TreeMap of fonts by family name.
*/
public TreeMap<String, String> getCreatedFontFamilyNames();
/**
* Returns all fonts installed in this environment.
*/
public Font[] getAllInstalledFonts();
public String[] getInstalledFontFamilyNames(Locale requestedLocale);
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.font;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.AccessController;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.plaf.FontUIResource;
import sun.security.action.GetPropertyAction;
/**
* A collection of utility methods.
*/
public final class FontUtilities {
public static final boolean isSolaris;
public static final boolean isLinux;
public static final boolean isSolaris8;
public static final boolean isSolaris9;
public static final boolean isOpenSolaris;
public static final boolean useT2K;
public static final boolean isWindows;
public static final boolean isOpenJDK;
static final String LUCIDA_FILE_NAME = "LucidaSansRegular.ttf";
// This static initializer block figures out the OS constants.
static {
String osName = AccessController.doPrivileged(
new GetPropertyAction("os.name", "unknownOS"));
isSolaris = osName.startsWith("SunOS");
isLinux = osName.startsWith("Linux");
String t2kStr = AccessController.doPrivileged(
new GetPropertyAction("sun.java2d.font.scaler"));
if (t2kStr != null) {
useT2K = "t2k".equals(t2kStr);
} else {
useT2K = false;
}
if (isSolaris) {
String version = AccessController.doPrivileged(
new GetPropertyAction("os.version", "0.0"));
isSolaris8 = version.startsWith("5.8");
isSolaris9 = version.startsWith("5.9");
float ver = Float.parseFloat(version);
if (ver > 5.10f) {
File f = new File("/etc/release");
String line = null;
try {
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(
fis, "ISO-8859-1");
BufferedReader br = new BufferedReader(isr);
line = br.readLine();
fis.close();
} catch (Exception ex) {
// Nothing to do here.
}
if (line != null && line.indexOf("OpenSolaris") >= 0) {
isOpenSolaris = true;
} else {
isOpenSolaris = false;
}
} else {
isOpenSolaris= false;
}
} else {
isSolaris8 = false;
isSolaris9 = false;
isOpenSolaris = false;
}
isWindows = osName.startsWith("Windows");
String jreLibDirName = AccessController.doPrivileged(
new GetPropertyAction("java.home","")) + File.separator + "lib";
String jreFontDirName = jreLibDirName + File.separator + "fonts";
File lucidaFile =
new File(jreFontDirName + File.separator + LUCIDA_FILE_NAME);
isOpenJDK = !lucidaFile.exists();
}
/**
* Referenced by code in the JDK which wants to test for the
* minimum char code for which layout may be required.
* Note that even basic latin text can benefit from ligatures,
* eg "ffi" but we presently apply those only if explicitly
* requested with TextAttribute.LIGATURES_ON.
* The value here indicates the lowest char code for which failing
* to invoke layout would prevent acceptable rendering.
*/
public static final int MIN_LAYOUT_CHARCODE = 0x0300;
/**
* Referenced by code in the JDK which wants to test for the
* maximum char code for which layout may be required.
* Note this does not account for supplementary characters
* where the caller interprets 'layout' to mean any case where
* one 'char' (ie the java type char) does not map to one glyph
*/
public static final int MAX_LAYOUT_CHARCODE = 0x206F;
private static boolean debugFonts = false;
private static Logger logger = null;
private static boolean logging;
static {
String debugLevel =
System.getProperty("sun.java2d.debugfonts");
if (debugLevel != null && !debugLevel.equals("false")) {
debugFonts = true;
logger = Logger.getLogger("sun.java2d");
if (debugLevel.equals("warning")) {
logger.setLevel(Level.WARNING);
} else if (debugLevel.equals("severe")) {
logger.setLevel(Level.SEVERE);
}
}
if (debugFonts) {
logger = Logger.getLogger("sun.java2d", null);
logging = logger.getLevel() != Level.OFF;
}
}
/**
* Calls the private getFont2D() method in java.awt.Font objects.
*
* @param font the font object to call
*
* @return the Font2D object returned by Font.getFont2D()
*/
public static Font2D getFont2D(Font font) {
return FontAccess.getFontAccess().getFont2D(font);
}
/**
* If there is anything in the text which triggers a case
* where char->glyph does not map 1:1 in straightforward
* left->right ordering, then this method returns true.
* Scripts which might require it but are not treated as such
* due to JDK implementations will not return true.
* ie a 'true' return is an indication of the treatment by
* the implementation.
* Whether supplementary characters should be considered is dependent
* on the needs of the caller. Since this method accepts the 'char' type
* then such chars are always represented by a pair. From a rendering
* perspective these will all (in the cases I know of) still be one
* unicode character -> one glyph. But if a caller is using this to
* discover any case where it cannot make naive assumptions about
* the number of chars, and how to index through them, then it may
* need the option to have a 'true' return in such a case.
*/
public static boolean isComplexText(char [] chs, int start, int limit) {
for (int i = start; i < limit; i++) {
if (chs[i] < MIN_LAYOUT_CHARCODE) {
continue;
}
else if (isNonSimpleChar(chs[i])) {
return true;
}
}
return false;
}
/* This is almost the same as the method above, except it takes a
* char which means it may include undecoded surrogate pairs.
* The distinction is made so that code which needs to identify all
* cases in which we do not have a simple mapping from
* char->unicode character->glyph can be be identified.
* For example measurement cannot simply sum advances of 'chars',
* the caret in editable text cannot advance one 'char' at a time, etc.
* These callers really are asking for more than whether 'layout'
* needs to be run, they need to know if they can assume 1->1
* char->glyph mapping.
*/
public static boolean isNonSimpleChar(char ch) {
return
isComplexCharCode(ch) ||
(ch >= CharToGlyphMapper.HI_SURROGATE_START &&
ch <= CharToGlyphMapper.LO_SURROGATE_END);
}
/* If the character code falls into any of a number of unicode ranges
* where we know that simple left->right layout mapping chars to glyphs
* 1:1 and accumulating advances is going to produce incorrect results,
* we want to know this so the caller can use a more intelligent layout
* approach. A caller who cares about optimum performance may want to
* check the first case and skip the method call if its in that range.
* Although there's a lot of tests in here, knowing you can skip
* CTL saves a great deal more. The rest of the checks are ordered
* so that rather than checking explicitly if (>= start & <= end)
* which would mean all ranges would need to be checked so be sure
* CTL is not needed, the method returns as soon as it recognises
* the code point is outside of a CTL ranges.
* NOTE: Since this method accepts an 'int' it is asssumed to properly
* represent a CHARACTER. ie it assumes the caller has already
* converted surrogate pairs into supplementary characters, and so
* can handle this case and doesn't need to be told such a case is
* 'complex'.
*/
public static boolean isComplexCharCode(int code) {
if (code < MIN_LAYOUT_CHARCODE || code > MAX_LAYOUT_CHARCODE) {
return false;
}
else if (code <= 0x036f) {
// Trigger layout for combining diacriticals 0x0300->0x036f
return true;
}
else if (code < 0x0590) {
// No automatic layout for Greek, Cyrillic, Armenian.
return false;
}
else if (code <= 0x06ff) {
// Hebrew 0590 - 05ff
// Arabic 0600 - 06ff
return true;
}
else if (code < 0x0900) {
return false; // Syriac and Thaana
}
else if (code <= 0x0e7f) {
// if Indic, assume shaping for conjuncts, reordering:
// 0900 - 097F Devanagari
// 0980 - 09FF Bengali
// 0A00 - 0A7F Gurmukhi
// 0A80 - 0AFF Gujarati
// 0B00 - 0B7F Oriya
// 0B80 - 0BFF Tamil
// 0C00 - 0C7F Telugu
// 0C80 - 0CFF Kannada
// 0D00 - 0D7F Malayalam
// 0D80 - 0DFF Sinhala
// 0E00 - 0E7F if Thai, assume shaping for vowel, tone marks
return true;
}
else if (code < 0x1780) {
return false;
}
else if (code <= 0x17ff) { // 1780 - 17FF Khmer
return true;
}
else if (code < 0x200c) {
return false;
}
else if (code <= 0x200d) { // zwj or zwnj
return true;
}
else if (code >= 0x202a && code <= 0x202e) { // directional control
return true;
}
else if (code >= 0x206a && code <= 0x206f) { // directional control
return true;
}
return false;
}
public static Logger getLogger() {
return logger;
}
public static boolean isLogging() {
return logging;
}
public static boolean debugFonts() {
return debugFonts;
}
// The following methods are used by Swing.
/* Revise the implementation to in fact mean "font is a composite font.
* This ensures that Swing components will always benefit from the
* fall back fonts
*/
public static boolean fontSupportsDefaultEncoding(Font font) {
return getFont2D(font) instanceof CompositeFont;
}
/**
* This method is provided for internal and exclusive use by Swing.
*
* It may be used in conjunction with fontSupportsDefaultEncoding(Font)
* In the event that a desktop properties font doesn't directly
* support the default encoding, (ie because the host OS supports
* adding support for the current locale automatically for native apps),
* then Swing calls this method to get a font which uses the specified
* font for the code points it covers, but also supports this locale
* just as the standard composite fonts do.
* Note: this will over-ride any setting where an application
* specifies it prefers locale specific composite fonts.
* The logic for this, is that this method is used only where the user or
* application has specified that the native L&F be used, and that
* we should honour that request to use the same font as native apps use.
*
* The behaviour of this method is to construct a new composite
* Font object that uses the specified physical font as its first
* component, and adds all the components of "dialog" as fall back
* components.
* The method currently assumes that only the size and style attributes
* are set on the specified font. It doesn't copy the font transform or
* other attributes because they aren't set on a font created from
* the desktop. This will need to be fixed if use is broadened.
*
* Operations such as Font.deriveFont will work properly on the
* font returned by this method for deriving a different point size.
* Additionally it tries to support a different style by calling
* getNewComposite() below. That also supports replacing slot zero
* with a different physical font but that is expected to be "rare".
* Deriving with a different style is needed because its been shown
* that some applications try to do this for Swing FontUIResources.
* Also operations such as new Font(font.getFontName(..), Font.PLAIN, 14);
* will NOT yield the same result, as the new underlying CompositeFont
* cannot be "looked up" in the font registry.
* This returns a FontUIResource as that is the Font sub-class needed
* by Swing.
* Suggested usage is something like :
* FontUIResource fuir;
* Font desktopFont = getDesktopFont(..);
* // NOTE even if fontSupportsDefaultEncoding returns true because
* // you get Tahoma and are running in an English locale, you may
* // still want to just call getCompositeFontUIResource() anyway
* // as only then will you get fallback fonts - eg for CJK.
* if (FontManager.fontSupportsDefaultEncoding(desktopFont)) {
* fuir = new FontUIResource(..);
* } else {
* fuir = FontManager.getCompositeFontUIResource(desktopFont);
* }
* return fuir;
*/
public static FontUIResource getCompositeFontUIResource(Font font) {
FontUIResource fuir =
new FontUIResource(font.getName(),font.getStyle(),font.getSize());
Font2D font2D = FontUtilities.getFont2D(font);
if (!(font2D instanceof PhysicalFont)) {
/* Swing should only be calling this when a font is obtained
* from desktop properties, so should generally be a physical font,
* an exception might be for names like "MS Serif" which are
* automatically mapped to "Serif", so there's no need to do
* anything special in that case. But note that suggested usage
* is first to call fontSupportsDefaultEncoding(Font) and this
* method should not be called if that were to return true.
*/
return fuir;
}
FontManager fm = FontManagerFactory.getInstance();
CompositeFont dialog2D =
(CompositeFont) fm.findFont2D("dialog", font.getStyle(), FontManager.NO_FALLBACK);
if (dialog2D == null) { /* shouldn't happen */
return fuir;
}
PhysicalFont physicalFont = (PhysicalFont)font2D;
CompositeFont compFont = new CompositeFont(physicalFont, dialog2D);
FontAccess.getFontAccess().setFont2D(fuir, compFont.handle);
/* marking this as a created font is needed as only created fonts
* copy their creator's handles.
*/
FontAccess.getFontAccess().setCreatedFont(fuir);
return fuir;
}
/* A small "map" from GTK/fontconfig names to the equivalent JDK
* logical font name.
*/
private static final String[][] nameMap = {
{"sans", "sansserif"},
{"sans-serif", "sansserif"},
{"serif", "serif"},
{"monospace", "monospaced"}
};
public static String mapFcName(String name) {
for (int i = 0; i < nameMap.length; i++) {
if (name.equals(nameMap[i][0])) {
return nameMap[i][1];
}
}
return null;
}
/* This is called by Swing passing in a fontconfig family name
* such as "sans". In return Swing gets a FontUIResource instance
* that has queried fontconfig to resolve the font(s) used for this.
* Fontconfig will if asked return a list of fonts to give the largest
* possible code point coverage.
* For now we use only the first font returned by fontconfig, and
* back it up with the most closely matching JDK logical font.
* Essentially this means pre-pending what we return now with fontconfig's
* preferred physical font. This could lead to some duplication in cases,
* if we already included that font later. We probably should remove such
* duplicates, but it is not a significant problem. It can be addressed
* later as part of creating a Composite which uses more of the
* same fonts as fontconfig. At that time we also should pay more
* attention to the special rendering instructions fontconfig returns,
* such as whether we should prefer embedded bitmaps over antialiasing.
* There's no way to express that via a Font at present.
*/
public static FontUIResource getFontConfigFUIR(String fcFamily,
int style, int size) {
String mapped = mapFcName(fcFamily);
if (mapped == null) {
mapped = "sansserif";
}
FontUIResource fuir;
FontManager fm = FontManagerFactory.getInstance();
if (fm instanceof SunFontManager) {
SunFontManager sfm = (SunFontManager) fm;
fuir = sfm.getFontConfigFUIR(mapped, style, size);
} else {
fuir = new FontUIResource(mapped, style, size);
}
return fuir;
}
/**
* Used by windows printing to assess if a font is likely to
* be layout compatible with JDK
* TrueType fonts should be, but if they have no GPOS table,
* but do have a GSUB table, then they are probably older
* fonts GDI handles differently.
*/
public static boolean textLayoutIsCompatible(Font font) {
Font2D font2D = getFont2D(font);
if (font2D instanceof TrueTypeFont) {
TrueTypeFont ttf = (TrueTypeFont) font2D;
return
ttf.getDirectoryEntry(TrueTypeFont.GSUBTag) == null ||
ttf.getDirectoryEntry(TrueTypeFont.GPOSTag) != null;
} else {
return false;
}
}
}
此差异已折叠。
此差异已折叠。
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.font;
import java.util.Locale;
import java.util.logging.Logger;
import sun.awt.SunHints;
import sun.awt.SunToolkit;
/**
* Small utility class to manage FontConfig.
*/
public class FontConfigManager {
static boolean fontConfigFailed = false;
/* This is populated by native */
private static final FontConfigInfo fcInfo = new FontConfigInfo();
/* Begin support for GTK Look and Feel - query libfontconfig and
* return a composite Font to Swing that uses the desktop font(s).
*/
/* These next three classes are just data structures.
*/
public static class FontConfigFont {
public String familyName; // eg Bitstream Vera Sans
public String styleStr; // eg Bold
public String fullName; // eg Bitstream Vera Sans Bold
public String fontFile; // eg /usr/X11/lib/fonts/foo.ttf
}
public static class FcCompFont {
public String fcName; // eg sans
public String fcFamily; // eg sans
public String jdkName; // eg sansserif
public int style; // eg 0=PLAIN
public FontConfigFont firstFont;
public FontConfigFont[] allFonts;
//boolean preferBitmaps; // if embedded bitmaps preferred over AA
public CompositeFont compFont; // null if not yet created/known.
}
public static class FontConfigInfo {
public int fcVersion;
public String[] cacheDirs = new String[4];
}
/* fontconfig recognises slants roman, italic, as well as oblique,
* and a slew of weights, where the ones that matter here are
* regular and bold.
* To fully qualify what we want, we can for example ask for (eg)
* Font.PLAIN : "serif:regular:roman"
* Font.BOLD : "serif:bold:roman"
* Font.ITALIC : "serif:regular:italic"
* Font.BOLD|Font.ITALIC : "serif:bold:italic"
*/
private static String[] fontConfigNames = {
"sans:regular:roman",
"sans:bold:roman",
"sans:regular:italic",
"sans:bold:italic",
"serif:regular:roman",
"serif:bold:roman",
"serif:regular:italic",
"serif:bold:italic",
"monospace:regular:roman",
"monospace:bold:roman",
"monospace:regular:italic",
"monospace:bold:italic",
};
/* This array has the array elements created in Java code and is
* passed down to native to be filled in.
*/
private FcCompFont[] fontConfigFonts;
/**
* Instantiates a new FontConfigManager getting the default instance
* of FontManager from the FontManagerFactory.
*/
public FontConfigManager() {
}
public static String[] getFontConfigNames() {
return fontConfigNames;
}
/* Called from code that needs to know what are the AA settings
* that apps using FC would pick up for the default desktop font.
* Note apps can change the default desktop font. etc, so this
* isn't certain to be right but its going to correct for most cases.
* Native return values map to the text aa values in sun.awt.SunHints.
* which is used to look up the renderinghint value object.
*/
public static Object getFontConfigAAHint() {
return getFontConfigAAHint("sans");
}
/* This is public solely so that for debugging purposes it can be called
* with other names, which might (eg) include a size, eg "sans-24"
* The return value is a text aa rendering hint value.
* Normally we should call the no-args version.
*/
public static Object getFontConfigAAHint(String fcFamily) {
if (FontUtilities.isWindows) {
return null;
} else {
int hint = getFontConfigAASettings(getFCLocaleStr(), fcFamily);
if (hint < 0) {
return null;
} else {
return SunHints.Value.get(SunHints.INTKEY_TEXT_ANTIALIASING,
hint);
}
}
}
private static String getFCLocaleStr() {
Locale l = SunToolkit.getStartupLocale();
String localeStr = l.getLanguage();
String country = l.getCountry();
if (!country.equals("")) {
localeStr = localeStr + "-" + country;
}
return localeStr;
}
/* This does cause the native libfontconfig to be loaded and unloaded,
* but it does not incur the overhead of initialisation of its
* data structures, so shouldn't have a measurable impact.
*/
public static native int getFontConfigVersion();
/* This can be made public if it's needed to force a re-read
* rather than using the cached values. The re-read would be needed
* only if some event signalled that the fontconfig has changed.
* In that event this method would need to return directly the array
* to be used by the caller in case it subsequently changed.
*/
public synchronized void initFontConfigFonts(boolean includeFallbacks) {
if (fontConfigFonts != null) {
if (!includeFallbacks || (fontConfigFonts[0].allFonts != null)) {
return;
}
}
if (FontUtilities.isWindows || fontConfigFailed) {
return;
}
long t0 = 0;
if (FontUtilities.isLogging()) {
t0 = System.nanoTime();
}
String[] fontConfigNames = FontConfigManager.getFontConfigNames();
FcCompFont[] fontArr = new FcCompFont[fontConfigNames.length];
for (int i = 0; i< fontArr.length; i++) {
fontArr[i] = new FcCompFont();
fontArr[i].fcName = fontConfigNames[i];
int colonPos = fontArr[i].fcName.indexOf(':');
fontArr[i].fcFamily = fontArr[i].fcName.substring(0, colonPos);
fontArr[i].jdkName = FontUtilities.mapFcName(fontArr[i].fcFamily);
fontArr[i].style = i % 4; // depends on array order.
}
getFontConfig(getFCLocaleStr(), fcInfo, fontArr, includeFallbacks);
/* If don't find anything (eg no libfontconfig), then just return */
for (int i = 0; i< fontArr.length; i++) {
FcCompFont fci = fontArr[i];
if (fci.firstFont == null) {
if (FontUtilities.isLogging()) {
Logger logger = FontUtilities.getLogger();
logger.info("Fontconfig returned no fonts.");
}
fontConfigFailed = true;
return;
}
}
fontConfigFonts = fontArr;
if (FontUtilities.isLogging()) {
Logger logger = FontUtilities.getLogger();
long t1 = System.nanoTime();
logger.info("Time spent accessing fontconfig="
+ ((t1 - t0) / 1000000) + "ms.");
for (int i = 0; i< fontConfigFonts.length; i++) {
FcCompFont fci = fontConfigFonts[i];
logger.info("FC font " + fci.fcName+" maps to family " +
fci.firstFont.familyName +
" in file " + fci.firstFont.fontFile);
if (fci.allFonts != null) {
for (int f=0;f<fci.allFonts.length;f++) {
FontConfigFont fcf = fci.allFonts[f];
logger.info("Family=" + fcf.familyName +
" Style="+ fcf.styleStr +
" Fullname="+fcf.fullName +
" File="+fcf.fontFile);
}
}
}
}
}
public PhysicalFont registerFromFcInfo(FcCompFont fcInfo) {
SunFontManager fm = SunFontManager.getInstance();
/* If it's a TTC file we need to know that as we will need to
* make sure we return the right font */
String fontFile = fcInfo.firstFont.fontFile;
int offset = fontFile.length()-4;
if (offset <= 0) {
return null;
}
String ext = fontFile.substring(offset).toLowerCase();
boolean isTTC = ext.equals(".ttc");
/* If this file is already registered, can just return its font.
* However we do need to check in case it's a TTC as we need
* a specific font, so rather than directly returning it, let
* findFont2D resolve that.
*/
PhysicalFont physFont = fm.getRegisteredFontFile(fontFile);
if (physFont != null) {
if (isTTC) {
Font2D f2d = fm.findFont2D(fcInfo.firstFont.familyName,
fcInfo.style,
FontManager.NO_FALLBACK);
if (f2d instanceof PhysicalFont) { /* paranoia */
return (PhysicalFont)f2d;
} else {
return null;
}
} else {
return physFont;
}
}
/* If the font may hide a JRE font (eg fontconfig says it is
* Lucida Sans), we want to use the JRE version, so make it
* point to the JRE font.
*/
physFont = fm.findJREDeferredFont(fcInfo.firstFont.familyName,
fcInfo.style);
/* It is also possible the font file is on the "deferred" list,
* in which case we can just initialise it now.
*/
if (physFont == null &&
fm.isDeferredFont(fontFile) == true) {
physFont = fm.initialiseDeferredFont(fcInfo.firstFont.fontFile);
/* use findFont2D to get the right font from TTC's */
if (physFont != null) {
if (isTTC) {
Font2D f2d = fm.findFont2D(fcInfo.firstFont.familyName,
fcInfo.style,
FontManager.NO_FALLBACK);
if (f2d instanceof PhysicalFont) { /* paranoia */
return (PhysicalFont)f2d;
} else {
return null;
}
} else {
return physFont;
}
}
}
/* In the majority of cases we reach here, and need to determine
* the type and rank to register the font.
*/
if (physFont == null) {
int fontFormat = SunFontManager.FONTFORMAT_NONE;
int fontRank = Font2D.UNKNOWN_RANK;
if (ext.equals(".ttf") || isTTC) {
fontFormat = SunFontManager.FONTFORMAT_TRUETYPE;
fontRank = Font2D.TTF_RANK;
} else if (ext.equals(".pfa") || ext.equals(".pfb")) {
fontFormat = SunFontManager.FONTFORMAT_TYPE1;
fontRank = Font2D.TYPE1_RANK;
}
physFont = fm.registerFontFile(fcInfo.firstFont.fontFile, null,
fontFormat, true, fontRank);
}
return physFont;
}
/*
* We need to return a Composite font which has as the font in
* its first slot one obtained from fontconfig.
*/
public CompositeFont getFontConfigFont(String name, int style) {
name = name.toLowerCase();
initFontConfigFonts(false);
FcCompFont fcInfo = null;
for (int i=0; i<fontConfigFonts.length; i++) {
if (name.equals(fontConfigFonts[i].fcFamily) &&
style == fontConfigFonts[i].style) {
fcInfo = fontConfigFonts[i];
break;
}
}
if (fcInfo == null) {
fcInfo = fontConfigFonts[0];
}
if (FontUtilities.isLogging()) {
FontUtilities.getLogger()
.info("FC name=" + name + " style=" + style +
" uses " + fcInfo.firstFont.familyName +
" in file: " + fcInfo.firstFont.fontFile);
}
if (fcInfo.compFont != null) {
return fcInfo.compFont;
}
/* jdkFont is going to be used for slots 1..N and as a fallback.
* Slot 0 will be the physical font from fontconfig.
*/
FontManager fm = FontManagerFactory.getInstance();
CompositeFont jdkFont = (CompositeFont)
fm.findFont2D(fcInfo.jdkName, style, FontManager.LOGICAL_FALLBACK);
if (fcInfo.firstFont.familyName == null ||
fcInfo.firstFont.fontFile == null) {
return (fcInfo.compFont = jdkFont);
}
/* First, see if the family and exact style is already registered.
* If it is, use it. If it's not, then try to register it.
* If that registration fails (signalled by null) just return the
* regular JDK composite.
* Algorithmically styled fonts won't match on exact style, so
* will fall through this code, but the regisration code will
* find that file already registered and return its font.
*/
FontFamily family = FontFamily.getFamily(fcInfo.firstFont.familyName);
PhysicalFont physFont = null;
if (family != null) {
Font2D f2D = family.getFontWithExactStyleMatch(fcInfo.style);
if (f2D instanceof PhysicalFont) {
physFont = (PhysicalFont)f2D;
}
}
if (physFont == null ||
!fcInfo.firstFont.fontFile.equals(physFont.platName)) {
physFont = registerFromFcInfo(fcInfo);
if (physFont == null) {
return (fcInfo.compFont = jdkFont);
}
family = FontFamily.getFamily(physFont.getFamilyName(null));
}
/* Now register the fonts in the family (the other styles) after
* checking that they aren't already registered and are actually in
* a different file. They may be the same file in CJK cases.
* For cases where they are different font files - eg as is common for
* Latin fonts, then we rely on fontconfig to report these correctly.
* Assume that all styles of this font are found by fontconfig,
* so we can find all the family members which must be registered
* together to prevent synthetic styling.
*/
for (int i=0; i<fontConfigFonts.length; i++) {
FcCompFont fc = fontConfigFonts[i];
if (fc != fcInfo &&
physFont.getFamilyName(null).equals(fc.firstFont.familyName) &&
!fc.firstFont.fontFile.equals(physFont.platName) &&
family.getFontWithExactStyleMatch(fc.style) == null) {
registerFromFcInfo(fontConfigFonts[i]);
}
}
/* Now we have a physical font. We will back this up with the JDK
* logical font (sansserif, serif, or monospaced) that corresponds
* to the Pango/GTK/FC logical font name.
*/
return (fcInfo.compFont = new CompositeFont(physFont, jdkFont));
}
/**
*
* @param locale
* @param fcFamily
* @return
*/
public FcCompFont[] getFontConfigFonts() {
return fontConfigFonts;
}
/* Return an array of FcCompFont structs describing the primary
* font located for each of fontconfig/GTK/Pango's logical font names.
*/
private static native void getFontConfig(String locale,
FontConfigInfo fcInfo,
FcCompFont[] fonts,
boolean includeFallbacks);
void populateFontConfig(FcCompFont[] fcInfo) {
fontConfigFonts = fcInfo;
}
FcCompFont[] loadFontConfig() {
initFontConfigFonts(true);
return fontConfigFonts;
}
FontConfigInfo getFontConfigInfo() {
initFontConfigFonts(true);
return fcInfo;
}
private static native int
getFontConfigAASettings(String locale, String fcFamily);
}
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册