Path: blob/master/src/java.desktop/share/classes/sun/font/FontUtilities.java
41154 views
/*1* Copyright (c) 2008, 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.font;2627import java.awt.Font;28import java.lang.ref.SoftReference;29import java.util.concurrent.ConcurrentHashMap;30import java.security.AccessController;3132import java.security.PrivilegedAction;33import javax.swing.plaf.FontUIResource;3435import sun.util.logging.PlatformLogger;3637/**38* A collection of utility methods.39*/40@SuppressWarnings("removal")41public final class FontUtilities {4243public static boolean isLinux;4445public static boolean isMacOSX;46public static boolean isMacOSX14;4748public static boolean useJDKScaler;4950public static boolean isWindows;5152private static boolean debugFonts = false;53private static PlatformLogger logger = null;54private static boolean logging;5556// This static initializer block figures out the OS constants.57static {5859AccessController.doPrivileged(new PrivilegedAction<Object>() {60@SuppressWarnings("deprecation") // PlatformLogger.setLevel is deprecated.61@Override62public Object run() {63String osName = System.getProperty("os.name", "unknownOS");6465isLinux = osName.startsWith("Linux");6667isMacOSX = osName.contains("OS X"); // TODO: MacOSX68if (isMacOSX) {69// os.version has values like 10.13.6, 10.14.670// If it is not positively recognised as 10.13 or less,71// assume it means 10.14 or some later version.72isMacOSX14 = true;73String version = System.getProperty("os.version", "");74if (version.startsWith("10.")) {75version = version.substring(3);76int periodIndex = version.indexOf('.');77if (periodIndex != -1) {78version = version.substring(0, periodIndex);79}80try {81int v = Integer.parseInt(version);82isMacOSX14 = (v >= 14);83} catch (NumberFormatException e) {84}85}86}87/* If set to "jdk", use the JDK's scaler rather than88* the platform one. This may be a no-op on platforms where89* JDK has been configured so that it always relies on the90* platform scaler. The principal case where it has an91* effect is that on Windows, 2D will never use GDI.92*/93String scalerStr = System.getProperty("sun.java2d.font.scaler");94if (scalerStr != null) {95useJDKScaler = "jdk".equals(scalerStr);96} else {97useJDKScaler = false;98}99isWindows = osName.startsWith("Windows");100String debugLevel =101System.getProperty("sun.java2d.debugfonts");102103if (debugLevel != null && !debugLevel.equals("false")) {104debugFonts = true;105logger = PlatformLogger.getLogger("sun.java2d");106if (debugLevel.equals("warning")) {107logger.setLevel(PlatformLogger.Level.WARNING);108} else if (debugLevel.equals("severe")) {109logger.setLevel(PlatformLogger.Level.SEVERE);110}111logging = logger.isEnabled();112}113114return null;115}116});117}118119/**120* Referenced by code in the JDK which wants to test for the121* minimum char code for which layout may be required.122* Note that even basic latin text can benefit from ligatures,123* eg "ffi" but we presently apply those only if explicitly124* requested with TextAttribute.LIGATURES_ON.125* The value here indicates the lowest char code for which failing126* to invoke layout would prevent acceptable rendering.127*/128public static final int MIN_LAYOUT_CHARCODE = 0x0300;129130/**131* Referenced by code in the JDK which wants to test for the132* maximum char code for which layout may be required.133* Note this does not account for supplementary characters134* where the caller interprets 'layout' to mean any case where135* one 'char' (ie the java type char) does not map to one glyph136*/137public static final int MAX_LAYOUT_CHARCODE = 0x206F;138139/**140* Calls the private getFont2D() method in java.awt.Font objects.141*142* @param font the font object to call143*144* @return the Font2D object returned by Font.getFont2D()145*/146public static Font2D getFont2D(Font font) {147return FontAccess.getFontAccess().getFont2D(font);148}149150/**151* Return true if there any characters which would trigger layout.152* This method considers supplementary characters to be simple,153* since we do not presently invoke layout on any code points in154* outside the BMP.155*/156public static boolean isComplexScript(char [] chs, int start, int limit) {157158for (int i = start; i < limit; i++) {159if (chs[i] < MIN_LAYOUT_CHARCODE) {160continue;161}162else if (isComplexCharCode(chs[i])) {163return true;164}165}166return false;167}168169/**170* If there is anything in the text which triggers a case171* where char->glyph does not map 1:1 in straightforward172* left->right ordering, then this method returns true.173* Scripts which might require it but are not treated as such174* due to JDK implementations will not return true.175* ie a 'true' return is an indication of the treatment by176* the implementation.177* Whether supplementary characters should be considered is dependent178* on the needs of the caller. Since this method accepts the 'char' type179* then such chars are always represented by a pair. From a rendering180* perspective these will all (in the cases I know of) still be one181* unicode character -> one glyph. But if a caller is using this to182* discover any case where it cannot make naive assumptions about183* the number of chars, and how to index through them, then it may184* need the option to have a 'true' return in such a case.185*/186public static boolean isComplexText(char [] chs, int start, int limit) {187188for (int i = start; i < limit; i++) {189if (chs[i] < MIN_LAYOUT_CHARCODE) {190continue;191}192else if (isNonSimpleChar(chs[i])) {193return true;194}195}196return false;197}198199/* This is almost the same as the method above, except it takes a200* char which means it may include undecoded surrogate pairs.201* The distinction is made so that code which needs to identify all202* cases in which we do not have a simple mapping from203* char->unicode character->glyph can be identified.204* For example measurement cannot simply sum advances of 'chars',205* the caret in editable text cannot advance one 'char' at a time, etc.206* These callers really are asking for more than whether 'layout'207* needs to be run, they need to know if they can assume 1->1208* char->glyph mapping.209*/210public static boolean isNonSimpleChar(char ch) {211return212isComplexCharCode(ch) ||213(ch >= CharToGlyphMapper.HI_SURROGATE_START &&214ch <= CharToGlyphMapper.LO_SURROGATE_END);215}216217/* If the character code falls into any of a number of unicode ranges218* where we know that simple left->right layout mapping chars to glyphs219* 1:1 and accumulating advances is going to produce incorrect results,220* we want to know this so the caller can use a more intelligent layout221* approach. A caller who cares about optimum performance may want to222* check the first case and skip the method call if its in that range.223* Although there's a lot of tests in here, knowing you can skip224* CTL saves a great deal more. The rest of the checks are ordered225* so that rather than checking explicitly if (>= start & <= end)226* which would mean all ranges would need to be checked so be sure227* CTL is not needed, the method returns as soon as it recognises228* the code point is outside of a CTL ranges.229* NOTE: Since this method accepts an 'int' it is asssumed to properly230* represent a CHARACTER. ie it assumes the caller has already231* converted surrogate pairs into supplementary characters, and so232* can handle this case and doesn't need to be told such a case is233* 'complex'.234*/235public static boolean isComplexCharCode(int code) {236237if (code < MIN_LAYOUT_CHARCODE || code > MAX_LAYOUT_CHARCODE) {238return false;239}240else if (code <= 0x036f) {241// Trigger layout for combining diacriticals 0x0300->0x036f242return true;243}244else if (code < 0x0590) {245// No automatic layout for Greek, Cyrillic, Armenian.246return false;247}248else if (code <= 0x06ff) {249// Hebrew 0590 - 05ff250// Arabic 0600 - 06ff251return true;252}253else if (code < 0x0900) {254return false; // Syriac and Thaana255}256else if (code <= 0x0e7f) {257// if Indic, assume shaping for conjuncts, reordering:258// 0900 - 097F Devanagari259// 0980 - 09FF Bengali260// 0A00 - 0A7F Gurmukhi261// 0A80 - 0AFF Gujarati262// 0B00 - 0B7F Oriya263// 0B80 - 0BFF Tamil264// 0C00 - 0C7F Telugu265// 0C80 - 0CFF Kannada266// 0D00 - 0D7F Malayalam267// 0D80 - 0DFF Sinhala268// 0E00 - 0E7F if Thai, assume shaping for vowel, tone marks269return true;270}271else if (code < 0x0f00) {272return false;273}274else if (code <= 0x0fff) { // U+0F00 - U+0FFF Tibetan275return true;276}277else if (code < 0x10A0) { // U+1000 - U+109F Myanmar278return true;279}280else if (code < 0x1100) {281return false;282}283else if (code < 0x11ff) { // U+1100 - U+11FF Old Hangul284return true;285}286else if (code < 0x1780) {287return false;288}289else if (code <= 0x17ff) { // 1780 - 17FF Khmer290return true;291}292else if (code < 0x200c) {293return false;294}295else if (code <= 0x200d) { // zwj or zwnj296return true;297}298else if (code >= 0x202a && code <= 0x202e) { // directional control299return true;300}301else if (code >= 0x206a && code <= 0x206f) { // directional control302return true;303}304return false;305}306307public static PlatformLogger getLogger() {308return logger;309}310311public static boolean isLogging() {312return logging;313}314315public static boolean debugFonts() {316return debugFonts;317}318319public static void logWarning(String s) {320getLogger().warning(s);321}322323public static void logInfo(String s) {324getLogger().info(s);325}326327public static void logSevere(String s) {328getLogger().severe(s);329}330331// The following methods are used by Swing.332333/* Revise the implementation to in fact mean "font is a composite font.334* This ensures that Swing components will always benefit from the335* fall back fonts336*/337public static boolean fontSupportsDefaultEncoding(Font font) {338return getFont2D(font) instanceof CompositeFont;339}340341/**342* This method is provided for internal and exclusive use by Swing.343*344* It may be used in conjunction with fontSupportsDefaultEncoding(Font)345* In the event that a desktop properties font doesn't directly346* support the default encoding, (ie because the host OS supports347* adding support for the current locale automatically for native apps),348* then Swing calls this method to get a font which uses the specified349* font for the code points it covers, but also supports this locale350* just as the standard composite fonts do.351* Note: this will over-ride any setting where an application352* specifies it prefers locale specific composite fonts.353* The logic for this, is that this method is used only where the user or354* application has specified that the native L&F be used, and that355* we should honour that request to use the same font as native apps use.356*357* The behaviour of this method is to construct a new composite358* Font object that uses the specified physical font as its first359* component, and adds all the components of "dialog" as fall back360* components.361* The method currently assumes that only the size and style attributes362* are set on the specified font. It doesn't copy the font transform or363* other attributes because they aren't set on a font created from364* the desktop. This will need to be fixed if use is broadened.365*366* Operations such as Font.deriveFont will work properly on the367* font returned by this method for deriving a different point size.368* Additionally it tries to support a different style by calling369* getNewComposite() below. That also supports replacing slot zero370* with a different physical font but that is expected to be "rare".371* Deriving with a different style is needed because its been shown372* that some applications try to do this for Swing FontUIResources.373* Also operations such as new Font(font.getFontName(..), Font.PLAIN, 14);374* will NOT yield the same result, as the new underlying CompositeFont375* cannot be "looked up" in the font registry.376* This returns a FontUIResource as that is the Font sub-class needed377* by Swing.378* Suggested usage is something like :379* FontUIResource fuir;380* Font desktopFont = getDesktopFont(..);381* if (FontManager.fontSupportsDefaultEncoding(desktopFont)) {382* fuir = new FontUIResource(desktopFont);383* } else {384* fuir = FontManager.getCompositeFontUIResource(desktopFont);385* }386* return fuir;387*/388private static volatile389SoftReference<ConcurrentHashMap<PhysicalFont, CompositeFont>>390compMapRef = new SoftReference<>(null);391392public static FontUIResource getCompositeFontUIResource(Font font) {393394FontUIResource fuir = new FontUIResource(font);395Font2D font2D = FontUtilities.getFont2D(font);396397if (!(font2D instanceof PhysicalFont)) {398/* Swing should only be calling this when a font is obtained399* from desktop properties, so should generally be a physical font,400* an exception might be for names like "MS Serif" which are401* automatically mapped to "Serif", so there's no need to do402* anything special in that case. But note that suggested usage403* is first to call fontSupportsDefaultEncoding(Font) and this404* method should not be called if that were to return true.405*/406return fuir;407}408409FontManager fm = FontManagerFactory.getInstance();410Font2D dialog = fm.findFont2D("dialog", font.getStyle(), FontManager.NO_FALLBACK);411// Should never be null, but MACOSX fonts are not CompositeFonts412if (dialog == null || !(dialog instanceof CompositeFont)) {413return fuir;414}415CompositeFont dialog2D = (CompositeFont)dialog;416PhysicalFont physicalFont = (PhysicalFont)font2D;417ConcurrentHashMap<PhysicalFont, CompositeFont> compMap = compMapRef.get();418if (compMap == null) { // Its been collected.419compMap = new ConcurrentHashMap<PhysicalFont, CompositeFont>();420compMapRef = new SoftReference<>(compMap);421}422CompositeFont compFont = compMap.get(physicalFont);423if (compFont == null) {424compFont = new CompositeFont(physicalFont, dialog2D);425compMap.put(physicalFont, compFont);426}427FontAccess.getFontAccess().setFont2D(fuir, compFont.handle);428/* marking this as a created font is needed as only created fonts429* copy their creator's handles.430*/431FontAccess.getFontAccess().setCreatedFont(fuir);432return fuir;433}434435/* A small "map" from GTK/fontconfig names to the equivalent JDK436* logical font name.437*/438private static final String[][] nameMap = {439{"sans", "sansserif"},440{"sans-serif", "sansserif"},441{"serif", "serif"},442{"monospace", "monospaced"}443};444445public static String mapFcName(String name) {446for (int i = 0; i < nameMap.length; i++) {447if (name.equals(nameMap[i][0])) {448return nameMap[i][1];449}450}451return null;452}453454455/* This is called by Swing passing in a fontconfig family name456* such as "sans". In return Swing gets a FontUIResource instance457* that has queried fontconfig to resolve the font(s) used for this.458* Fontconfig will if asked return a list of fonts to give the largest459* possible code point coverage.460* For now we use only the first font returned by fontconfig, and461* back it up with the most closely matching JDK logical font.462* Essentially this means pre-pending what we return now with fontconfig's463* preferred physical font. This could lead to some duplication in cases,464* if we already included that font later. We probably should remove such465* duplicates, but it is not a significant problem. It can be addressed466* later as part of creating a Composite which uses more of the467* same fonts as fontconfig. At that time we also should pay more468* attention to the special rendering instructions fontconfig returns,469* such as whether we should prefer embedded bitmaps over antialiasing.470* There's no way to express that via a Font at present.471*/472public static FontUIResource getFontConfigFUIR(String fcFamily,473int style, int size) {474475String mapped = mapFcName(fcFamily);476if (mapped == null) {477mapped = "sansserif";478}479480FontUIResource fuir;481FontManager fm = FontManagerFactory.getInstance();482if (fm instanceof SunFontManager) {483SunFontManager sfm = (SunFontManager) fm;484fuir = sfm.getFontConfigFUIR(mapped, style, size);485} else {486fuir = new FontUIResource(mapped, style, size);487}488return fuir;489}490491492/**493* Used by windows printing to assess if a font is likely to494* be layout compatible with JDK495* TrueType fonts should be, but if they have no GPOS table,496* but do have a GSUB table, then they are probably older497* fonts GDI handles differently.498*/499public static boolean textLayoutIsCompatible(Font font) {500501Font2D font2D = getFont2D(font);502if (font2D instanceof TrueTypeFont) {503TrueTypeFont ttf = (TrueTypeFont) font2D;504return505ttf.getDirectoryEntry(TrueTypeFont.GSUBTag) == null ||506ttf.getDirectoryEntry(TrueTypeFont.GPOSTag) != null;507} else {508return false;509}510}511512}513514515