Path: blob/master/src/java.desktop/unix/classes/sun/awt/X11FontManager.java
41152 views
/*1* Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.awt;2627import java.awt.GraphicsEnvironment;28import java.io.BufferedReader;29import java.io.File;30import java.io.FileReader;31import java.io.IOException;32import java.io.StreamTokenizer;33import java.util.HashMap;34import java.util.HashSet;35import java.util.Locale;36import java.util.Map;37import java.util.NoSuchElementException;38import java.util.StringTokenizer;39import java.util.Vector;4041import javax.swing.plaf.FontUIResource;42import sun.font.MFontConfiguration;43import sun.font.CompositeFont;44import sun.font.FontManager;45import sun.font.SunFontManager;46import sun.font.FcFontConfiguration;47import sun.font.FontAccess;48import sun.font.FontUtilities;49import sun.font.NativeFont;50import sun.util.logging.PlatformLogger;5152/**53* The X11 implementation of {@link FontManager}.54*/55public final class X11FontManager extends FcFontManager {5657// constants identifying XLFD and font ID fields58private static final int FOUNDRY_FIELD = 1;59private static final int FAMILY_NAME_FIELD = 2;60private static final int WEIGHT_NAME_FIELD = 3;61private static final int SLANT_FIELD = 4;62private static final int SETWIDTH_NAME_FIELD = 5;63private static final int ADD_STYLE_NAME_FIELD = 6;64private static final int PIXEL_SIZE_FIELD = 7;65private static final int POINT_SIZE_FIELD = 8;66private static final int RESOLUTION_X_FIELD = 9;67private static final int RESOLUTION_Y_FIELD = 10;68private static final int SPACING_FIELD = 11;69private static final int AVERAGE_WIDTH_FIELD = 12;70private static final int CHARSET_REGISTRY_FIELD = 13;71private static final int CHARSET_ENCODING_FIELD = 14;7273/*74* fontNameMap is a map from a fontID (which is a substring of an XLFD like75* "-monotype-arial-bold-r-normal-iso8859-7")76* to font file path like77* /usr/openwin/lib/locale/iso_8859_7/X11/fonts/TrueType/ArialBoldItalic.ttf78* It's used in a couple of methods like79* getFileNameFomPlatformName(..) to help locate the font file.80* We use this substring of a full XLFD because the font configuration files81* define the XLFDs in a way that's easier to make into a request.82* E.g., the -0-0-0-0-p-0- reported by X is -*-%d-*-*-p-*- in the font83* configuration files. We need to remove that part for comparisons.84*/85private static Map<String, String> fontNameMap = new HashMap<>();8687/*88* xlfdMap is a map from a platform path like89* /usr/openwin/lib/locale/ja/X11/fonts/TT/HG-GothicB.ttf to an XLFD like90* "-ricoh-hg gothic b-medium-r-normal--0-0-0-0-m-0-jisx0201.1976-0"91* Because there may be multiple native names, because the font is used92* to support multiple X encodings for example, the value of an entry in93* this map is always a vector where we store all the native names.94* For fonts which we don't understand the key isn't a pathname, its95* the full XLFD string like :-96* "-ricoh-hg gothic b-medium-r-normal--0-0-0-0-m-0-jisx0201.1976-0"97*/98private static Map<String, Vector<String>> xlfdMap = new HashMap<>();99100/* xFontDirsMap is also a map from a font ID to a font filepath.101* The difference from fontNameMap is just that it does not have102* resolved symbolic links. Normally this is not interesting except103* that we need to know the directory in which a font was found to104* add it to the X font server path, since although the files may105* be linked, the fonts.dir is different and specific to the encoding106* handled by that directory. This map is nulled out after use to free107* heap space. If the optimal path is taken, such that all fonts in108* font configuration files are referenced by filename, then the font109* dir can be directly derived as its parent directory.110* If a font is used by two XLFDs, each corresponding to a different111* X11 font directory, then precautions must be taken to include both112* directories.113*/114private static Map<String, String> xFontDirsMap;115116/*117* This is the set of font directories needed to be on the X font path118* to enable AWT heavyweights to find all of the font configuration fonts.119* It is populated by :120* - awtfontpath entries in the fontconfig.properties121* - parent directories of "core" fonts used in the fontconfig.properties122* - looking up font dirs in the xFontDirsMap where the key is a fontID123* (cut down version of the XLFD read from the font configuration file).124* This set is nulled out after use to free heap space.125*/126private static HashSet<String> fontConfigDirs = null;127128/*129* Used to eliminate redundant work. When a font directory is130* registered it added to this list. Subsequent registrations for the131* same directory can then be skipped by checking this Map.132* Access to this map is not synchronised here since creation133* of the singleton GE instance is already synchronised and that is134* the only code path that accesses this map.135*/136private static HashMap<String, Object> registeredDirs = new HashMap<>();137138/* Array of directories to be added to the X11 font path.139* Used by static method called from Toolkits which use X11 fonts.140* Specifically this means MToolkit141*/142private static String[] fontdirs = null;143144public static X11FontManager getInstance() {145return (X11FontManager) SunFontManager.getInstance();146}147148/**149* Takes family name property in the following format:150* "-linotype-helvetica-medium-r-normal-sans-*-%d-*-*-p-*-iso8859-1"151* and returns the name of the corresponding physical font.152* This code is used to resolve font configuration fonts, and expects153* only to get called for these fonts.154*/155@Override156public String getFileNameFromPlatformName(String platName) {157158/* If the FontConfig file doesn't use xlfds, or its159* FcFontConfiguration, this may be already a file name.160*/161if (platName.startsWith("/")) {162return platName;163}164165String fileName = null;166String fontID = specificFontIDForName(platName);167168/* If the font filename has been explicitly assigned in the169* font configuration file, use it. This avoids accessing170* the wrong fonts on Linux, where different fonts (some171* of which may not be usable by 2D) may share the same172* specific font ID. It may also speed up the lookup.173*/174fileName = super.getFileNameFromPlatformName(platName);175if (fileName != null) {176if (isHeadless() && fileName.startsWith("-")) {177/* if it's headless, no xlfd should be used */178return null;179}180if (fileName.startsWith("/")) {181/* If a path is assigned in the font configuration file,182* it is required that the config file also specify using the183* new awtfontpath key the X11 font directories184* which must be added to the X11 font path to support185* AWT access to that font. For that reason we no longer186* have code here to add the parent directory to the list187* of font config dirs, since the parent directory may not188* be sufficient if fonts are symbolically linked to a189* different directory.190*191* Add this XLFD (platform name) to the list of known192* ones for this file.193*/194Vector<String> xVal = xlfdMap.get(fileName);195if (xVal == null) {196/* Try to be robust on Linux distros which move fonts197* around by verifying that the fileName represents a198* file that exists. If it doesn't, set it to null199* to trigger a search.200*/201if (getFontConfiguration().needToSearchForFile(fileName)) {202fileName = null;203}204if (fileName != null) {205xVal = new Vector<>();206xVal.add(platName);207xlfdMap.put(fileName, xVal);208}209} else {210if (!xVal.contains(platName)) {211xVal.add(platName);212}213}214}215if (fileName != null) {216fontNameMap.put(fontID, fileName);217return fileName;218}219}220221if (fontID != null) {222fileName = fontNameMap.get(fontID);223if (fontPath == null &&224(fileName == null || !fileName.startsWith("/"))) {225if (FontUtilities.debugFonts()) {226FontUtilities.logWarning("** Registering all font paths because " +227"can't find file for " + platName);228}229fontPath = getPlatformFontPath(noType1Font);230registerFontDirs(fontPath);231if (FontUtilities.debugFonts()) {232FontUtilities.logWarning("** Finished registering all font paths");233}234fileName = fontNameMap.get(fontID);235}236if (fileName == null && !isHeadless()) {237/* Query X11 directly to see if this font is available238* as a native font.239*/240fileName = getX11FontName(platName);241}242if (fileName == null) {243fontID = switchFontIDForName(platName);244fileName = fontNameMap.get(fontID);245}246if (fileName != null) {247fontNameMap.put(fontID, fileName);248}249}250return fileName;251}252253@Override254protected String[] getNativeNames(String fontFileName,255String platformName) {256Vector<String> nativeNames;257if ((nativeNames=xlfdMap.get(fontFileName))==null) {258if (platformName == null) {259return null;260} else {261/* back-stop so that at least the name used in the262* font configuration file is known as a native name263*/264String []natNames = new String[1];265natNames[0] = platformName;266return natNames;267}268} else {269int len = nativeNames.size();270return nativeNames.toArray(new String[len]);271}272}273274/* NOTE: this method needs to be executed in a privileged context.275* The superclass constructor which is the primary caller of276* this method executes entirely in such a context. Additionally277* the loadFonts() method does too. So all should be well.278279*/280@Override281protected void registerFontDir(String path) {282/* fonts.dir file format looks like :-283* 47284* Arial.ttf -monotype-arial-regular-r-normal--0-0-0-0-p-0-iso8859-1285* Arial-Bold.ttf -monotype-arial-bold-r-normal--0-0-0-0-p-0-iso8859-1286* ...287*/288if (FontUtilities.debugFonts()) {289FontUtilities.logInfo("ParseFontDir " + path);290}291File fontsDotDir = new File(path + File.separator + "fonts.dir");292FileReader fr = null;293try {294if (fontsDotDir.canRead()) {295fr = new FileReader(fontsDotDir);296BufferedReader br = new BufferedReader(fr, 8192);297StreamTokenizer st = new StreamTokenizer(br);298st.eolIsSignificant(true);299int ttype = st.nextToken();300if (ttype == StreamTokenizer.TT_NUMBER) {301int numEntries = (int)st.nval;302ttype = st.nextToken();303if (ttype == StreamTokenizer.TT_EOL) {304st.resetSyntax();305st.wordChars(32, 127);306st.wordChars(128 + 32, 255);307st.whitespaceChars(0, 31);308309for (int i=0; i < numEntries; i++) {310ttype = st.nextToken();311if (ttype == StreamTokenizer.TT_EOF) {312break;313}314if (ttype != StreamTokenizer.TT_WORD) {315break;316}317int breakPos = st.sval.indexOf(' ');318if (breakPos <= 0) {319/* On TurboLinux 8.0 a fonts.dir file had320* a line with integer value "24" which321* appeared to be the number of remaining322* entries in the file. This didn't add to323* the value on the first line of the file.324* Seemed like XFree86 didn't like this line325* much either. It failed to parse the file.326* Ignore lines like this completely, and327* don't let them count as an entry.328*/329numEntries++;330ttype = st.nextToken();331if (ttype != StreamTokenizer.TT_EOL) {332break;333}334335continue;336}337if (st.sval.charAt(0) == '!') {338/* TurboLinux 8.0 comment line: ignore.339* can't use st.commentChar('!') to just340* skip because this line mustn't count341* against numEntries.342*/343numEntries++;344ttype = st.nextToken();345if (ttype != StreamTokenizer.TT_EOL) {346break;347}348continue;349}350String fileName = st.sval.substring(0, breakPos);351/* TurboLinux 8.0 uses some additional syntax to352* indicate algorithmic styling values.353* Ignore ':' separated files at the beginning354* of the fileName355*/356int lastColon = fileName.lastIndexOf(':');357if (lastColon > 0) {358if (lastColon+1 >= fileName.length()) {359continue;360}361fileName = fileName.substring(lastColon+1);362}363String fontPart = st.sval.substring(breakPos+1);364String fontID = specificFontIDForName(fontPart);365String sVal = fontNameMap.get(fontID);366367if (FontUtilities.debugFonts()) {368FontUtilities.logInfo("file=" + fileName +369" xlfd=" + fontPart);370FontUtilities.logInfo("fontID=" + fontID +371" sVal=" + sVal);372}373String fullPath = null;374try {375File file = new File(path,fileName);376/* we may have a resolved symbolic link377* this becomes important for an xlfd we378* still need to know the location it was379* found to update the X server font path380* for use by AWT heavyweights - and when 2D381* wants to use the native rasteriser.382*/383if (xFontDirsMap == null) {384xFontDirsMap = new HashMap<>();385}386xFontDirsMap.put(fontID, path);387fullPath = file.getCanonicalPath();388} catch (IOException e) {389fullPath = path + File.separator + fileName;390}391Vector<String> xVal = xlfdMap.get(fullPath);392if (FontUtilities.debugFonts()) {393FontUtilities.logInfo("fullPath=" + fullPath +394" xVal=" + xVal);395}396if ((xVal == null || !xVal.contains(fontPart)) &&397(sVal == null) || !sVal.startsWith("/")) {398if (FontUtilities.debugFonts()) {399FontUtilities.logInfo("Map fontID:"+fontID +400"to file:" + fullPath);401}402fontNameMap.put(fontID, fullPath);403if (xVal == null) {404xVal = new Vector<>();405xlfdMap.put (fullPath, xVal);406}407xVal.add(fontPart);408}409410ttype = st.nextToken();411if (ttype != StreamTokenizer.TT_EOL) {412break;413}414}415}416}417fr.close();418}419} catch (IOException ioe1) {420} finally {421if (fr != null) {422try {423fr.close();424} catch (IOException ioe2) {425}426}427}428}429430@Override431public void loadFonts() {432super.loadFonts();433/* These maps are greatly expanded during a loadFonts but434* can be reset to their initial state afterwards.435* Since preferLocaleFonts() and preferProportionalFonts() will436* trigger a partial repopulating from the FontConfiguration437* it has to be the inital (empty) state for the latter two, not438* simply nulling out.439* xFontDirsMap is a special case in that the implementation440* will typically not ever need to initialise it so it can be null.441*/442xFontDirsMap = null;443xlfdMap = new HashMap<>(1);444fontNameMap = new HashMap<>(1);445}446447private static String getX11FontName(String platName) {448String xlfd = platName.replaceAll("%d", "*");449if (NativeFont.fontExists(xlfd)) {450return xlfd;451} else {452return null;453}454}455456private boolean isHeadless() {457GraphicsEnvironment ge =458GraphicsEnvironment.getLocalGraphicsEnvironment();459return GraphicsEnvironment.isHeadless();460}461462private String specificFontIDForName(String name) {463464int[] hPos = new int[14];465int hyphenCnt = 1;466int pos = 1;467468while (pos != -1 && hyphenCnt < 14) {469pos = name.indexOf('-', pos);470if (pos != -1) {471hPos[hyphenCnt++] = pos;472pos++;473}474}475476if (hyphenCnt != 14) {477if (FontUtilities.debugFonts()) {478FontUtilities.logSevere("Font Configuration Font ID is malformed:" + name);479}480return name; // what else can we do?481}482483String sb = name.substring(hPos[FAMILY_NAME_FIELD-1], hPos[SETWIDTH_NAME_FIELD])484+ name.substring(hPos[CHARSET_REGISTRY_FIELD-1]);485String retval = sb.toLowerCase(Locale.ENGLISH);486return retval;487}488489private String switchFontIDForName(String name) {490491int[] hPos = new int[14];492int hyphenCnt = 1;493int pos = 1;494495while (pos != -1 && hyphenCnt < 14) {496pos = name.indexOf('-', pos);497if (pos != -1) {498hPos[hyphenCnt++] = pos;499pos++;500}501}502503if (hyphenCnt != 14) {504if (FontUtilities.debugFonts()) {505FontUtilities.logSevere("Font Configuration Font ID is malformed:" + name);506}507return name; // what else can we do?508}509510String slant = name.substring(hPos[SLANT_FIELD-1]+1,511hPos[SLANT_FIELD]);512String family = name.substring(hPos[FAMILY_NAME_FIELD-1]+1,513hPos[FAMILY_NAME_FIELD]);514String registry = name.substring(hPos[CHARSET_REGISTRY_FIELD-1]+1,515hPos[CHARSET_REGISTRY_FIELD]);516String encoding = name.substring(hPos[CHARSET_ENCODING_FIELD-1]+1);517518if (slant.equals("i")) {519slant = "o";520} else if (slant.equals("o")) {521slant = "i";522}523// workaround for #4471000524if (family.equals("itc zapfdingbats")525&& registry.equals("sun")526&& encoding.equals("fontspecific")){527registry = "adobe";528}529String sb = name.substring(hPos[FAMILY_NAME_FIELD-1], hPos[SLANT_FIELD-1]+1)530+ slant531+ name.substring(hPos[SLANT_FIELD], hPos[SETWIDTH_NAME_FIELD]+1)532+ registry533+ name.substring(hPos[CHARSET_ENCODING_FIELD-1]);534String retval = sb.toLowerCase(Locale.ENGLISH);535return retval;536}537538/**539* Returns the face name for the given XLFD.540*/541public String getFileNameFromXLFD(String name) {542String fileName = null;543String fontID = specificFontIDForName(name);544if (fontID != null) {545fileName = fontNameMap.get(fontID);546if (fileName == null) {547fontID = switchFontIDForName(name);548fileName = fontNameMap.get(fontID);549}550if (fileName == null) {551fileName = getDefaultFontFile();552}553}554return fileName;555}556557/* Register just the paths, (it doesn't register the fonts).558* If a font configuration file has specified a baseFontPath559* fontPath is just those directories, unless on usage we560* find it doesn't contain what we need for the logical fonts.561* Otherwise, we register all the paths on Solaris, because562* the fontPath we have here is the complete one from563* parsing /var/sadm/install/contents, not just564* what's on the X font path (may be this should be565* changed).566* But for now what it means is that if we didn't do567* this then if the font weren't listed anywhere on the568* less complete font path we'd trigger loadFonts which569* actually registers the fonts. This may actually be570* the right thing tho' since that would also set up571* the X font path without which we wouldn't be able to572* display some "native" fonts.573* So something to revisit is that probably fontPath574* here ought to be only the X font path + jre font dir.575* loadFonts should have a separate native call to576* get the rest of the platform font path.577*578* Registering the directories can now be avoided in the579* font configuration initialisation when filename entries580* exist in the font configuration file for all fonts.581* (Perhaps a little confusingly a filename entry is582* actually keyed using the XLFD used in the font entries,583* and it maps *to* a real filename).584* In the event any are missing, registration of all585* directories will be invoked to find the real files.586*587* But registering the directory performed other588* functions such as filling in the map of all native names589* for the font. So when this method isn't invoked, they still590* must be found. This is mitigated by getNativeNames now591* being able to return at least the platform name, but mostly592* by ensuring that when a filename key is found, that593* xlfd key is stored as one of the set of platform names594* for the font. Its a set because typical font configuration595* files reference the same CJK font files using multiple596* X11 encodings. For the code that adds this to the map597* see X11GE.getFileNameFromPlatformName(..)598* If you don't get all of these then some code points may599* not use the Xserver, and will not get the PCF bitmaps600* that are available for some point sizes.601* So, in the event that there is such a problem,602* unconditionally making this call may be necessary, at603* some cost to JRE start-up604*/605@Override606protected void registerFontDirs(String pathName) {607608StringTokenizer parser = new StringTokenizer(pathName,609File.pathSeparator);610try {611while (parser.hasMoreTokens()) {612String dirPath = parser.nextToken();613if (dirPath != null && !registeredDirs.containsKey(dirPath)) {614registeredDirs.put(dirPath, null);615registerFontDir(dirPath);616}617}618} catch (NoSuchElementException e) {619}620}621622// An X font spec (xlfd) includes an encoding. The same TrueType font file623// may be referenced from different X font directories in font.dir files624// to support use in multiple encodings by X apps.625// So for the purposes of font configuration logical fonts where AWT626// heavyweights need to access the font via X APIs we need to ensure that627// the directory for precisely the encodings needed by this are added to628// the x font path. This requires that we note the platform names629// specified in font configuration files and use that to identify the630// X font directory that contains a font.dir file for that platform name631// and add it to the X font path (if display is local)632// Here we make use of an already built map of xlfds to font locations633// to add the font location to the set of those required to build the634// x font path needed by AWT.635// These are added to the x font path later.636// All this is necessary because on Solaris the font.dir directories637// may contain not real font files, but symbolic links to the actual638// location but that location is not suitable for the x font path, since639// it probably doesn't have a font.dir at all and certainly not one640// with the required encodings641// If the fontconfiguration file is properly set up so that all fonts642// are mapped to files then we will never trigger initialising643// xFontDirsMap (it will be null). In this case the awtfontpath entries644// must specify all the X11 directories needed by AWT.645@Override646protected void addFontToPlatformFontPath(String platformName) {647// Lazily initialize fontConfigDirs.648getPlatformFontPathFromFontConfig();649if (xFontDirsMap != null) {650String fontID = specificFontIDForName(platformName);651String dirName = xFontDirsMap.get(fontID);652if (dirName != null) {653fontConfigDirs.add(dirName);654}655}656return;657}658659private void getPlatformFontPathFromFontConfig() {660if (fontConfigDirs == null) {661fontConfigDirs = getFontConfiguration().getAWTFontPathSet();662if (FontUtilities.debugFonts() && fontConfigDirs != null) {663String[] names = fontConfigDirs.toArray(new String[0]);664for (int i=0;i<names.length;i++) {665FontUtilities.logInfo("awtfontpath : " + names[i]);666}667}668}669}670671@Override672protected void registerPlatformFontsUsedByFontConfiguration() {673// Lazily initialize fontConfigDirs.674getPlatformFontPathFromFontConfig();675if (fontConfigDirs == null) {676return;677}678if (FontUtilities.isLinux) {679fontConfigDirs.add(jreLibDirName+File.separator+"oblique-fonts");680}681fontdirs = fontConfigDirs.toArray(new String[0]);682}683684// Implements SunGraphicsEnvironment.createFontConfiguration.685protected FontConfiguration createFontConfiguration() {686/* The logic here decides whether to use a preconfigured687* fontconfig.properties file, or synthesise one using platform APIs.688* On Solaris we try to use the689* pre-configured ones, but if the files it specifies are missing690* we fail-safe to synthesising one. This might happen if Solaris691* changes its fonts.692* For Linux we require an exact match of distro and version to693* use the preconfigured file.694* If synthesising fails, we fall back to any preconfigured file695* and do the best we can.696*/697FontConfiguration mFontConfig = new MFontConfiguration(this);698if ((FontUtilities.isLinux && !mFontConfig.foundOsSpecificFile())) {699FcFontConfiguration fcFontConfig =700new FcFontConfiguration(this);701if (fcFontConfig.init()) {702return fcFontConfig;703}704}705mFontConfig.init();706return mFontConfig;707}708709public FontConfiguration710createFontConfiguration(boolean preferLocaleFonts,711boolean preferPropFonts) {712713return new MFontConfiguration(this,714preferLocaleFonts, preferPropFonts);715}716717protected synchronized String getFontPath(boolean noType1Fonts) {718isHeadless(); // make sure GE is inited, as its the X11 lock.719return getFontPathNative(noType1Fonts, true);720}721722@Override723protected FontUIResource getFontConfigFUIR(String family, int style, int size) {724725CompositeFont font2D = getFontConfigManager().getFontConfigFont(family, style);726727if (font2D == null) { // Not expected, just a precaution.728return new FontUIResource(family, style, size);729}730731/* The name of the font will be that of the physical font in slot,732* but by setting the handle to that of the CompositeFont it733* renders as that CompositeFont.734* It also needs to be marked as a created font which is the735* current mechanism to signal that deriveFont etc must copy736* the handle from the original font.737*/738FontUIResource fuir =739new FontUIResource(font2D.getFamilyName(null), style, size);740FontAccess.getFontAccess().setFont2D(fuir, font2D.handle);741FontAccess.getFontAccess().setCreatedFont(fuir);742return fuir;743}744}745746747