FcFontConfiguration.java 19.6 KB
Newer Older
1
/*
2
 * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * 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
7
 * published by the Free Software Foundation.  Oracle designates this
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
10 11 12 13 14 15 16 17
 *
 * 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
18
 * 2 along with this work; if not, write to the Free Software Foundation,
19 20
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * 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.
24 25 26 27 28 29 30 31 32 33 34 35
 */

package sun.font;

import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
36
import java.nio.charset.StandardCharsets;
37
import java.nio.file.Files;
38 39 40 41
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;
import java.util.Scanner;
R
rkennke 已提交
42
import sun.awt.FcFontManager;
43 44 45 46 47
import sun.awt.FontConfiguration;
import sun.awt.FontDescriptor;
import sun.awt.SunToolkit;
import sun.font.CompositeFontDescriptor;
import sun.font.FontManager;
R
rkennke 已提交
48 49 50
import sun.font.FontConfigManager.FontConfigInfo;
import sun.font.FontConfigManager.FcCompFont;
import sun.font.FontConfigManager.FontConfigFont;
51
import sun.java2d.SunGraphicsEnvironment;
52
import sun.util.logging.PlatformLogger;
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

public class FcFontConfiguration extends FontConfiguration {

    /** Version of the cache file format understood by this code.
     * Its part of the file name so that we can rev this at
     * any time, even in a minor JDK update.
     * It is stored as the value of the "version" property.
     * This is distinct from the version of "libfontconfig" that generated
     * the cached results, and which is the "fcversion" property in the file.
     * {@code FontConfiguration.getVersion()} also returns a version string,
     * and has meant the version of the fontconfiguration.properties file
     * that was read. Since this class doesn't use such files, then what
     * that really means is whether the methods on this class return
     * values that are compatible with the classes that do directly read
     * from such files. It is a compatible subset of version "1".
     */
    private static final String fileVersion = "1";
    private String fcInfoFileName = null;

    private FcCompFont[] fcCompFonts = null;

R
rkennke 已提交
74 75
    public FcFontConfiguration(SunFontManager fm) {
        super(fm);
76 77 78 79
        init();
    }

    /* This isn't called but is needed to satisfy super-class contract. */
R
rkennke 已提交
80
    public FcFontConfiguration(SunFontManager fm,
81 82
                               boolean preferLocaleFonts,
                               boolean preferPropFonts) {
R
rkennke 已提交
83
        super(fm, preferLocaleFonts, preferPropFonts);
84 85 86 87 88 89 90 91 92
        init();
    }

    @Override
    public synchronized boolean init() {
        if (fcCompFonts != null) {
            return true;
        }

93
        setFontConfiguration();
94
        readFcInfo();
R
rkennke 已提交
95
        FcFontManager fm = (FcFontManager) fontManager;
R
rkennke 已提交
96
        FontConfigManager fcm = fm.getFontConfigManager();
97
        if (fcCompFonts == null) {
R
rkennke 已提交
98
            fcCompFonts = fcm.loadFontConfig();
99 100 101 102
            if (fcCompFonts != null) {
                try {
                    writeFcInfo();
                } catch (Exception e) {
R
rkennke 已提交
103
                    if (FontUtilities.debugFonts()) {
104
                        warning("Exception writing fcInfo " + e);
105 106
                    }
                }
R
rkennke 已提交
107
            } else if (FontUtilities.debugFonts()) {
108
                warning("Failed to get info from libfontconfig");
109 110
            }
        } else {
R
rkennke 已提交
111
            fcm.populateFontConfig(fcCompFonts);
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        }

        if (fcCompFonts == null) {
            return false; // couldn't load fontconfig.
        }

        // NB already in a privileged block from SGE
        String javaHome = System.getProperty("java.home");
        if (javaHome == null) {
            throw new Error("java.home property not set");
        }
        String javaLib = javaHome + File.separator + "lib";
        getInstalledFallbackFonts(javaLib);

        return true;
    }

    @Override
    public String getFallbackFamilyName(String fontName,
                                        String defaultFallback) {
        // maintain compatibility with old font.properties files, which either
        // had aliases for TimesRoman & Co. or defined mappings for them.
        String compatibilityName = getCompatibilityFamilyName(fontName);
        if (compatibilityName != null) {
            return compatibilityName;
        }
        return defaultFallback;
    }

    @Override
    protected String
        getFaceNameFromComponentFontName(String componentFontName) {
        return null;
    }

    @Override
    protected String
        getFileNameFromComponentFontName(String componentFontName) {
        return null;
    }

    @Override
    public String getFileNameFromPlatformName(String platformName) {
        /* Platform name is the file name, but rather than returning
         * the arg, return null*/
        return null;
    }

    @Override
    protected Charset getDefaultFontCharset(String fontName) {
        return Charset.forName("ISO8859_1");
    }

    @Override
    protected String getEncoding(String awtFontName,
                                 String characterSubsetName) {
        return "default";
    }

    @Override
    protected void initReorderMap() {
        reorderMap = new HashMap();
    }

    @Override
177 178 179 180 181 182
    protected FontDescriptor[] buildFontDescriptors(int fontIndex, int styleIndex) {
        CompositeFontDescriptor[] cfi = get2DCompositeFontInfo();
        int idx = fontIndex * NUM_STYLES + styleIndex;
        String[] componentFaceNames = cfi[idx].getComponentFaceNames();
        FontDescriptor[] ret = new FontDescriptor[componentFaceNames.length];
        for (int i = 0; i < componentFaceNames.length; i++) {
183
            ret[i] = new FontDescriptor(componentFaceNames[i], StandardCharsets.ISO_8859_1.newEncoder(), new int[0]);
184 185 186
        }

        return ret;
187 188 189 190 191 192 193 194 195 196
    }

    @Override
    public int getNumberCoreFonts() {
        return 1;
    }

    @Override
    public String[] getPlatformFontNames() {
        HashSet<String> nameSet = new HashSet<String>();
R
rkennke 已提交
197
        FcFontManager fm = (FcFontManager) fontManager;
R
rkennke 已提交
198 199
        FontConfigManager fcm = fm.getFontConfigManager();
        FcCompFont[] fcCompFonts = fcm.loadFontConfig();
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        for (int i=0; i<fcCompFonts.length; i++) {
            for (int j=0; j<fcCompFonts[i].allFonts.length; j++) {
                nameSet.add(fcCompFonts[i].allFonts[j].fontFile);
            }
        }
        return nameSet.toArray(new String[0]);
    }

    @Override
    public String getExtraFontPath() {
        return null;
    }

    @Override
    public boolean needToSearchForFile(String fileName) {
        return false;
    }

    private FontConfigFont[] getFcFontList(FcCompFont[] fcFonts,
                                           String fontname, int style) {

        if (fontname.equals("dialog")) {
            fontname = "sansserif";
        } else if (fontname.equals("dialoginput")) {
            fontname = "monospaced";
        }
        for (int i=0; i<fcFonts.length; i++) {
            if (fontname.equals(fcFonts[i].jdkName) &&
                style == fcFonts[i].style) {
                return fcFonts[i].allFonts;
            }
        }
        return fcFonts[0].allFonts;
    }

    @Override
    public CompositeFontDescriptor[] get2DCompositeFontInfo() {

R
rkennke 已提交
238
        FcFontManager fm = (FcFontManager) fontManager;
R
rkennke 已提交
239 240
        FontConfigManager fcm = fm.getFontConfigManager();
        FcCompFont[] fcCompFonts = fcm.loadFontConfig();
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

        CompositeFontDescriptor[] result =
                new CompositeFontDescriptor[NUM_FONTS * NUM_STYLES];

        for (int fontIndex = 0; fontIndex < NUM_FONTS; fontIndex++) {
            String fontName = publicFontNames[fontIndex];

            for (int styleIndex = 0; styleIndex < NUM_STYLES; styleIndex++) {

                String faceName = fontName + "." + styleNames[styleIndex];
                FontConfigFont[] fcFonts =
                    getFcFontList(fcCompFonts,
                                  fontNames[fontIndex], styleIndex);

                int numFonts = fcFonts.length;
                // fall back fonts listed in the lib/fonts/fallback directory
                if (installedFallbackFontFiles != null) {
                    numFonts += installedFallbackFontFiles.length;
                }

                String[] fileNames = new String[numFonts];
262
                String[] faceNames = new String[numFonts];
263 264 265 266

                int index;
                for (index = 0; index < fcFonts.length; index++) {
                    fileNames[index] = fcFonts[index].fontFile;
267
                    faceNames[index] = fcFonts[index].familyName;
268 269 270
                }

                if (installedFallbackFontFiles != null) {
271 272 273
                    System.arraycopy(installedFallbackFontFiles, 0,
                                     fileNames, fcFonts.length,
                                     installedFallbackFontFiles.length);
274 275 276 277 278 279
                }

                result[fontIndex * NUM_STYLES + styleIndex]
                        = new CompositeFontDescriptor(
                            faceName,
                            1,
280
                            faceNames,
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
                            fileNames,
                            null, null);
            }
        }
        return result;
    }

    /**
     * Gets the OS version string from a Linux release-specific file.
     */
    private String getVersionString(File f){
        try {
            Scanner sc  = new Scanner(f);
            return sc.findInLine("(\\d)+((\\.)(\\d)+)*");
        }
        catch (Exception e){
        }
        return null;
    }

    /**
     * Sets the OS name and version from environment information.
     */
    @Override
    protected void setOsNameAndVersion() {

        super.setOsNameAndVersion();

        if (!osName.equals("Linux")) {
            return;
        }
        try {
            File f;
            if ((f = new File("/etc/lsb-release")).canRead()) {
                    /* Ubuntu and (perhaps others) use only lsb-release.
                     * Syntax and encoding is compatible with java properties.
                     * For Ubuntu the ID is "Ubuntu".
                     */
                    Properties props = new Properties();
                    props.load(new FileInputStream(f));
                    osName = props.getProperty("DISTRIB_ID");
                    osVersion =  props.getProperty("DISTRIB_RELEASE");
            } else if ((f = new File("/etc/redhat-release")).canRead()) {
                osName = "RedHat";
                osVersion = getVersionString(f);
            } else if ((f = new File("/etc/SuSE-release")).canRead()) {
                osName = "SuSE";
                osVersion = getVersionString(f);
            } else if ((f = new File("/etc/turbolinux-release")).canRead()) {
                osName = "Turbo";
                osVersion = getVersionString(f);
            } else if ((f = new File("/etc/fedora-release")).canRead()) {
                osName = "Fedora";
                osVersion = getVersionString(f);
            }
        } catch (Exception e) {
R
rkennke 已提交
337
            if (FontUtilities.debugFonts()) {
338
                warning("Exception identifying Linux distro.");
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
            }
        }
    }

    private File getFcInfoFile() {
        if (fcInfoFileName == null) {
            // NB need security permissions to get true IP address, and
            // we should have those as the whole initialisation is in a
            // doPrivileged block. But in this case no exception is thrown,
            // and it returns the loop back address, and so we end up with
            // "localhost"
            String hostname;
            try {
                hostname = InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                hostname = "localhost";
            }
            String userDir = System.getProperty("user.home");
            String version = System.getProperty("java.version");
            String fs = File.separator;
            String dir = userDir+fs+".java"+fs+"fonts"+fs+version;
            String lang = SunToolkit.getStartupLocale().getLanguage();
            String name = "fcinfo-"+fileVersion+"-"+hostname+"-"+
                osName+"-"+osVersion+"-"+lang+".properties";
            fcInfoFileName = dir+fs+name;
        }
        return new File(fcInfoFileName);
    }

    private void writeFcInfo() {
        Properties props = new Properties();
        props.setProperty("version", fileVersion);
R
rkennke 已提交
371
        FcFontManager fm = (FcFontManager) fontManager;
R
rkennke 已提交
372 373
        FontConfigManager fcm = fm.getFontConfigManager();
        FontConfigInfo fcInfo = fcm.getFontConfigInfo();
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        props.setProperty("fcversion", Integer.toString(fcInfo.fcVersion));
        if (fcInfo.cacheDirs != null) {
            for (int i=0;i<fcInfo.cacheDirs.length;i++) {
                if (fcInfo.cacheDirs[i] != null) {
                   props.setProperty("cachedir."+i,  fcInfo.cacheDirs[i]);
                }
            }
        }
        for (int i=0; i<fcCompFonts.length; i++) {
            FcCompFont fci = fcCompFonts[i];
            String styleKey = fci.jdkName+"."+fci.style;
            props.setProperty(styleKey+".length",
                              Integer.toString(fci.allFonts.length));
            for (int j=0; j<fci.allFonts.length; j++) {
                props.setProperty(styleKey+"."+j+".family",
                                  fci.allFonts[j].familyName);
                props.setProperty(styleKey+"."+j+".file",
                                  fci.allFonts[j].fontFile);
            }
        }
        try {
            /* This writes into a temp file then renames when done.
             * Since the rename is an atomic action within the same
             * directory no client will ever see a partially written file.
             */
            File fcInfoFile = getFcInfoFile();
            File dir = fcInfoFile.getParentFile();
            dir.mkdirs();
402
            File tempFile = Files.createTempFile(dir.toPath(), "fcinfo", null).toFile();
403 404 405 406 407
            FileOutputStream fos = new FileOutputStream(tempFile);
            props.store(fos,
                      "JDK Font Configuration Generated File: *Do Not Edit*");
            fos.close();
            boolean renamed = tempFile.renameTo(fcInfoFile);
R
rkennke 已提交
408
            if (!renamed && FontUtilities.debugFonts()) {
409
                System.out.println("rename failed");
410
                warning("Failed renaming file to "+ getFcInfoFile());
411 412
            }
        } catch (Exception e) {
R
rkennke 已提交
413
            if (FontUtilities.debugFonts()) {
414
                warning("IOException writing to "+ getFcInfoFile());
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
            }
        }
    }

    /* We want to be able to use this cache instead of invoking
     * fontconfig except when we can detect the system cache has changed.
     * But there doesn't seem to be a way to find the location of
     * the system cache.
     */
    private void readFcInfo() {
        File fcFile = getFcInfoFile();
        if (!fcFile.exists()) {
            return;
        }
        Properties props = new Properties();
R
rkennke 已提交
430
        FcFontManager fm = (FcFontManager) fontManager;
R
rkennke 已提交
431
        FontConfigManager fcm = fm.getFontConfigManager();
432 433 434 435 436
        try {
            FileInputStream fis = new FileInputStream(fcFile);
            props.load(fis);
            fis.close();
        } catch (IOException e) {
R
rkennke 已提交
437
            if (FontUtilities.debugFonts()) {
438
                warning("IOException reading from "+fcFile.toString());
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
            }
            return;
        }
        String version = (String)props.get("version");
        if (version == null || !version.equals(fileVersion)) {
            return;
        }

        // If there's a new, different fontconfig installed on the
        // system, we invalidate our fontconfig file.
        String fcVersionStr = (String)props.get("fcversion");
        if (fcVersionStr != null) {
            int fcVersion;
            try {
                fcVersion = Integer.parseInt(fcVersionStr);
                if (fcVersion != 0 &&
R
rkennke 已提交
455
                    fcVersion != fcm.getFontConfigVersion()) {
456 457 458
                    return;
                }
            } catch (Exception e) {
R
rkennke 已提交
459
                if (FontUtilities.debugFonts()) {
460
                    warning("Exception parsing version " + fcVersionStr);
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
                }
                return;
            }
        }

        // If we can locate the fontconfig cache dirs, then compare the
        // time stamp of those with our properties file. If we are out
        // of date then re-generate.
        long lastModified = fcFile.lastModified();
        int cacheDirIndex = 0;
        while (cacheDirIndex<4) { // should never be more than 2 anyway.
            String dir = (String)props.get("cachedir."+cacheDirIndex);
            if (dir == null) {
                break;
            }
            File dirFile = new File(dir);
            if (dirFile.exists() && dirFile.lastModified() > lastModified) {
                return;
            }
            cacheDirIndex++;
        }

        String[] names = { "sansserif", "serif", "monospaced" };
        String[] fcnames = { "sans", "serif", "monospace" };
        int namesLen = names.length;
        int numStyles = 4;
        FcCompFont[] fci = new FcCompFont[namesLen*numStyles];

        try {
            for (int i=0; i<namesLen; i++) {
                for (int s=0; s<numStyles; s++) {
                    int index = i*numStyles+s;
                    fci[index] = new FcCompFont();
                    String key = names[i]+"."+s;
                    fci[index].jdkName = names[i];
                    fci[index].fcFamily = fcnames[i];
                    fci[index].style = s;
                    String lenStr = (String)props.get(key+".length");
                    int nfonts = Integer.parseInt(lenStr);
                    if (nfonts <= 0) {
                        return; // bad file
                    }
                    fci[index].allFonts = new FontConfigFont[nfonts];
                    for (int f=0; f<nfonts; f++) {
                        fci[index].allFonts[f] = new FontConfigFont();
                        String fkey = key+"."+f+".family";
                        String family = (String)props.get(fkey);
                        fci[index].allFonts[f].familyName = family;
                        fkey = key+"."+f+".file";
                        String file = (String)props.get(fkey);
                        if (file == null) {
                            return; // bad file
                        }
                        fci[index].allFonts[f].fontFile = file;
                    }
                    fci[index].firstFont =  fci[index].allFonts[0];

                }
            }
            fcCompFonts = fci;
        } catch (Throwable t) {
R
rkennke 已提交
522
            if (FontUtilities.debugFonts()) {
523
                warning(t.toString());
524 525 526
            }
        }
    }
527 528 529 530 531

    private static void warning(String msg) {
        PlatformLogger logger = PlatformLogger.getLogger("sun.awt.FontConfiguration");
        logger.warning(msg);
    }
532
}