Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/awt/Font.java
38829 views
/*1* Copyright (c) 1995, 2013, 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 java.awt;2627import java.awt.font.FontRenderContext;28import java.awt.font.GlyphVector;29import java.awt.font.LineMetrics;30import java.awt.font.TextAttribute;31import java.awt.font.TextLayout;32import java.awt.geom.AffineTransform;33import java.awt.geom.Point2D;34import java.awt.geom.Rectangle2D;35import java.awt.peer.FontPeer;36import java.io.*;37import java.lang.ref.SoftReference;38import java.nio.file.Files;39import java.security.AccessController;40import java.security.PrivilegedExceptionAction;41import java.text.AttributedCharacterIterator.Attribute;42import java.text.CharacterIterator;43import java.text.StringCharacterIterator;44import java.util.Hashtable;45import java.util.Locale;46import java.util.Map;47import sun.font.StandardGlyphVector;4849import sun.font.AttributeMap;50import sun.font.AttributeValues;51import sun.font.CompositeFont;52import sun.font.CreatedFontTracker;53import sun.font.Font2D;54import sun.font.Font2DHandle;55import sun.font.FontAccess;56import sun.font.FontManager;57import sun.font.FontManagerFactory;58import sun.font.FontUtilities;59import sun.font.GlyphLayout;60import sun.font.FontLineMetrics;61import sun.font.CoreMetrics;6263import static sun.font.EAttribute.*;6465/**66* The <code>Font</code> class represents fonts, which are used to67* render text in a visible way.68* A font provides the information needed to map sequences of69* <em>characters</em> to sequences of <em>glyphs</em>70* and to render sequences of glyphs on <code>Graphics</code> and71* <code>Component</code> objects.72*73* <h3>Characters and Glyphs</h3>74*75* A <em>character</em> is a symbol that represents an item such as a letter,76* a digit, or punctuation in an abstract way. For example, <code>'g'</code>,77* LATIN SMALL LETTER G, is a character.78* <p>79* A <em>glyph</em> is a shape used to render a character or a sequence of80* characters. In simple writing systems, such as Latin, typically one glyph81* represents one character. In general, however, characters and glyphs do not82* have one-to-one correspondence. For example, the character 'á'83* LATIN SMALL LETTER A WITH ACUTE, can be represented by84* two glyphs: one for 'a' and one for '´'. On the other hand, the85* two-character string "fi" can be represented by a single glyph, an86* "fi" ligature. In complex writing systems, such as Arabic or the South87* and South-East Asian writing systems, the relationship between characters88* and glyphs can be more complicated and involve context-dependent selection89* of glyphs as well as glyph reordering.90*91* A font encapsulates the collection of glyphs needed to render a selected set92* of characters as well as the tables needed to map sequences of characters to93* corresponding sequences of glyphs.94*95* <h3>Physical and Logical Fonts</h3>96*97* The Java Platform distinguishes between two kinds of fonts:98* <em>physical</em> fonts and <em>logical</em> fonts.99* <p>100* <em>Physical</em> fonts are the actual font libraries containing glyph data101* and tables to map from character sequences to glyph sequences, using a font102* technology such as TrueType or PostScript Type 1.103* All implementations of the Java Platform must support TrueType fonts;104* support for other font technologies is implementation dependent.105* Physical fonts may use names such as Helvetica, Palatino, HonMincho, or106* any number of other font names.107* Typically, each physical font supports only a limited set of writing108* systems, for example, only Latin characters or only Japanese and Basic109* Latin.110* The set of available physical fonts varies between configurations.111* Applications that require specific fonts can bundle them and instantiate112* them using the {@link #createFont createFont} method.113* <p>114* <em>Logical</em> fonts are the five font families defined by the Java115* platform which must be supported by any Java runtime environment:116* Serif, SansSerif, Monospaced, Dialog, and DialogInput.117* These logical fonts are not actual font libraries. Instead, the logical118* font names are mapped to physical fonts by the Java runtime environment.119* The mapping is implementation and usually locale dependent, so the look120* and the metrics provided by them vary.121* Typically, each logical font name maps to several physical fonts in order to122* cover a large range of characters.123* <p>124* Peered AWT components, such as {@link Label Label} and125* {@link TextField TextField}, can only use logical fonts.126* <p>127* For a discussion of the relative advantages and disadvantages of using128* physical or logical fonts, see the129* <a href="http://www.oracle.com/technetwork/java/javase/tech/faq-jsp-138165.html">Internationalization FAQ</a>130* document.131*132* <h3>Font Faces and Names</h3>133*134* A <code>Font</code>135* can have many faces, such as heavy, medium, oblique, gothic and136* regular. All of these faces have similar typographic design.137* <p>138* There are three different names that you can get from a139* <code>Font</code> object. The <em>logical font name</em> is simply the140* name that was used to construct the font.141* The <em>font face name</em>, or just <em>font name</em> for142* short, is the name of a particular font face, like Helvetica Bold. The143* <em>family name</em> is the name of the font family that determines the144* typographic design across several faces, like Helvetica.145* <p>146* The <code>Font</code> class represents an instance of a font face from147* a collection of font faces that are present in the system resources148* of the host system. As examples, Arial Bold and Courier Bold Italic149* are font faces. There can be several <code>Font</code> objects150* associated with a font face, each differing in size, style, transform151* and font features.152* <p>153* The {@link GraphicsEnvironment#getAllFonts() getAllFonts} method154* of the <code>GraphicsEnvironment</code> class returns an155* array of all font faces available in the system. These font faces are156* returned as <code>Font</code> objects with a size of 1, identity157* transform and default font features. These158* base fonts can then be used to derive new <code>Font</code> objects159* with varying sizes, styles, transforms and font features via the160* <code>deriveFont</code> methods in this class.161*162* <h3>Font and TextAttribute</h3>163*164* <p><code>Font</code> supports most165* <code>TextAttribute</code>s. This makes some operations, such as166* rendering underlined text, convenient since it is not167* necessary to explicitly construct a <code>TextLayout</code> object.168* Attributes can be set on a Font by constructing or deriving it169* using a <code>Map</code> of <code>TextAttribute</code> values.170*171* <p>The values of some <code>TextAttributes</code> are not172* serializable, and therefore attempting to serialize an instance of173* <code>Font</code> that has such values will not serialize them.174* This means a Font deserialized from such a stream will not compare175* equal to the original Font that contained the non-serializable176* attributes. This should very rarely pose a problem177* since these attributes are typically used only in special178* circumstances and are unlikely to be serialized.179*180* <ul>181* <li><code>FOREGROUND</code> and <code>BACKGROUND</code> use182* <code>Paint</code> values. The subclass <code>Color</code> is183* serializable, while <code>GradientPaint</code> and184* <code>TexturePaint</code> are not.</li>185* <li><code>CHAR_REPLACEMENT</code> uses186* <code>GraphicAttribute</code> values. The subclasses187* <code>ShapeGraphicAttribute</code> and188* <code>ImageGraphicAttribute</code> are not serializable.</li>189* <li><code>INPUT_METHOD_HIGHLIGHT</code> uses190* <code>InputMethodHighlight</code> values, which are191* not serializable. See {@link java.awt.im.InputMethodHighlight}.</li>192* </ul>193*194* <p>Clients who create custom subclasses of <code>Paint</code> and195* <code>GraphicAttribute</code> can make them serializable and196* avoid this problem. Clients who use input method highlights can197* convert these to the platform-specific attributes for that198* highlight on the current platform and set them on the Font as199* a workaround.200*201* <p>The <code>Map</code>-based constructor and202* <code>deriveFont</code> APIs ignore the FONT attribute, and it is203* not retained by the Font; the static {@link #getFont} method should204* be used if the FONT attribute might be present. See {@link205* java.awt.font.TextAttribute#FONT} for more information.</p>206*207* <p>Several attributes will cause additional rendering overhead208* and potentially invoke layout. If a <code>Font</code> has such209* attributes, the <code>{@link #hasLayoutAttributes()}</code> method210* will return true.</p>211*212* <p>Note: Font rotations can cause text baselines to be rotated. In213* order to account for this (rare) possibility, font APIs are214* specified to return metrics and take parameters 'in215* baseline-relative coordinates'. This maps the 'x' coordinate to216* the advance along the baseline, (positive x is forward along the217* baseline), and the 'y' coordinate to a distance along the218* perpendicular to the baseline at 'x' (positive y is 90 degrees219* clockwise from the baseline vector). APIs for which this is220* especially important are called out as having 'baseline-relative221* coordinates.'222*/223public class Font implements java.io.Serializable224{225private static class FontAccessImpl extends FontAccess {226public Font2D getFont2D(Font font) {227return font.getFont2D();228}229230public void setFont2D(Font font, Font2DHandle handle) {231font.font2DHandle = handle;232}233234public void setCreatedFont(Font font) {235font.createdFont = true;236}237238public boolean isCreatedFont(Font font) {239return font.createdFont;240}241}242243static {244/* ensure that the necessary native libraries are loaded */245Toolkit.loadLibraries();246initIDs();247FontAccess.setFontAccess(new FontAccessImpl());248}249250/**251* This is now only used during serialization. Typically252* it is null.253*254* @serial255* @see #getAttributes()256*/257private Hashtable<Object, Object> fRequestedAttributes;258259/*260* Constants to be used for logical font family names.261*/262263/**264* A String constant for the canonical family name of the265* logical font "Dialog". It is useful in Font construction266* to provide compile-time verification of the name.267* @since 1.6268*/269public static final String DIALOG = "Dialog";270271/**272* A String constant for the canonical family name of the273* logical font "DialogInput". It is useful in Font construction274* to provide compile-time verification of the name.275* @since 1.6276*/277public static final String DIALOG_INPUT = "DialogInput";278279/**280* A String constant for the canonical family name of the281* logical font "SansSerif". It is useful in Font construction282* to provide compile-time verification of the name.283* @since 1.6284*/285public static final String SANS_SERIF = "SansSerif";286287/**288* A String constant for the canonical family name of the289* logical font "Serif". It is useful in Font construction290* to provide compile-time verification of the name.291* @since 1.6292*/293public static final String SERIF = "Serif";294295/**296* A String constant for the canonical family name of the297* logical font "Monospaced". It is useful in Font construction298* to provide compile-time verification of the name.299* @since 1.6300*/301public static final String MONOSPACED = "Monospaced";302303/*304* Constants to be used for styles. Can be combined to mix305* styles.306*/307308/**309* The plain style constant.310*/311public static final int PLAIN = 0;312313/**314* The bold style constant. This can be combined with the other style315* constants (except PLAIN) for mixed styles.316*/317public static final int BOLD = 1;318319/**320* The italicized style constant. This can be combined with the other321* style constants (except PLAIN) for mixed styles.322*/323public static final int ITALIC = 2;324325/**326* The baseline used in most Roman scripts when laying out text.327*/328public static final int ROMAN_BASELINE = 0;329330/**331* The baseline used in ideographic scripts like Chinese, Japanese,332* and Korean when laying out text.333*/334public static final int CENTER_BASELINE = 1;335336/**337* The baseline used in Devanigiri and similar scripts when laying338* out text.339*/340public static final int HANGING_BASELINE = 2;341342/**343* Identify a font resource of type TRUETYPE.344* Used to specify a TrueType font resource to the345* {@link #createFont} method.346* The TrueType format was extended to become the OpenType347* format, which adds support for fonts with Postscript outlines,348* this tag therefore references these fonts, as well as those349* with TrueType outlines.350* @since 1.3351*/352353public static final int TRUETYPE_FONT = 0;354355/**356* Identify a font resource of type TYPE1.357* Used to specify a Type1 font resource to the358* {@link #createFont} method.359* @since 1.5360*/361public static final int TYPE1_FONT = 1;362363/**364* The logical name of this <code>Font</code>, as passed to the365* constructor.366* @since JDK1.0367*368* @serial369* @see #getName370*/371protected String name;372373/**374* The style of this <code>Font</code>, as passed to the constructor.375* This style can be PLAIN, BOLD, ITALIC, or BOLD+ITALIC.376* @since JDK1.0377*378* @serial379* @see #getStyle()380*/381protected int style;382383/**384* The point size of this <code>Font</code>, rounded to integer.385* @since JDK1.0386*387* @serial388* @see #getSize()389*/390protected int size;391392/**393* The point size of this <code>Font</code> in <code>float</code>.394*395* @serial396* @see #getSize()397* @see #getSize2D()398*/399protected float pointSize;400401/**402* The platform specific font information.403*/404private transient FontPeer peer;405private transient long pData; // native JDK1.1 font pointer406private transient Font2DHandle font2DHandle;407408private transient AttributeValues values;409private transient boolean hasLayoutAttributes;410411/*412* If the origin of a Font is a created font then this attribute413* must be set on all derived fonts too.414*/415private transient boolean createdFont = false;416417/*418* This is true if the font transform is not identity. It419* is used to avoid unnecessary instantiation of an AffineTransform.420*/421private transient boolean nonIdentityTx;422423/*424* A cached value used when a transform is required for internal425* use. This must not be exposed to callers since AffineTransform426* is mutable.427*/428private static final AffineTransform identityTx = new AffineTransform();429430/*431* JDK 1.1 serialVersionUID432*/433private static final long serialVersionUID = -4206021311591459213L;434435/**436* Gets the peer of this <code>Font</code>.437* @return the peer of the <code>Font</code>.438* @since JDK1.1439* @deprecated Font rendering is now platform independent.440*/441@Deprecated442public FontPeer getPeer(){443return getPeer_NoClientCode();444}445// NOTE: This method is called by privileged threads.446// We implement this functionality in a package-private method447// to insure that it cannot be overridden by client subclasses.448// DO NOT INVOKE CLIENT CODE ON THIS THREAD!449@SuppressWarnings("deprecation")450final FontPeer getPeer_NoClientCode() {451if(peer == null) {452Toolkit tk = Toolkit.getDefaultToolkit();453this.peer = tk.getFontPeer(name, style);454}455return peer;456}457458/**459* Return the AttributeValues object associated with this460* font. Most of the time, the internal object is null.461* If required, it will be created from the 'standard'462* state on the font. Only non-default values will be463* set in the AttributeValues object.464*465* <p>Since the AttributeValues object is mutable, and it466* is cached in the font, care must be taken to ensure that467* it is not mutated.468*/469private AttributeValues getAttributeValues() {470if (values == null) {471AttributeValues valuesTmp = new AttributeValues();472valuesTmp.setFamily(name);473valuesTmp.setSize(pointSize); // expects the float value.474475if ((style & BOLD) != 0) {476valuesTmp.setWeight(2); // WEIGHT_BOLD477}478479if ((style & ITALIC) != 0) {480valuesTmp.setPosture(.2f); // POSTURE_OBLIQUE481}482valuesTmp.defineAll(PRIMARY_MASK); // for streaming compatibility483values = valuesTmp;484}485486return values;487}488489private Font2D getFont2D() {490FontManager fm = FontManagerFactory.getInstance();491if (fm.usingPerAppContextComposites() &&492font2DHandle != null &&493font2DHandle.font2D instanceof CompositeFont &&494((CompositeFont)(font2DHandle.font2D)).isStdComposite()) {495return fm.findFont2D(name, style,496FontManager.LOGICAL_FALLBACK);497} else if (font2DHandle == null) {498font2DHandle =499fm.findFont2D(name, style,500FontManager.LOGICAL_FALLBACK).handle;501}502/* Do not cache the de-referenced font2D. It must be explicitly503* de-referenced to pick up a valid font in the event that the504* original one is marked invalid505*/506return font2DHandle.font2D;507}508509/**510* Creates a new <code>Font</code> from the specified name, style and511* point size.512* <p>513* The font name can be a font face name or a font family name.514* It is used together with the style to find an appropriate font face.515* When a font family name is specified, the style argument is used to516* select the most appropriate face from the family. When a font face517* name is specified, the face's style and the style argument are518* merged to locate the best matching font from the same family.519* For example if face name "Arial Bold" is specified with style520* <code>Font.ITALIC</code>, the font system looks for a face in the521* "Arial" family that is bold and italic, and may associate the font522* instance with the physical font face "Arial Bold Italic".523* The style argument is merged with the specified face's style, not524* added or subtracted.525* This means, specifying a bold face and a bold style does not526* double-embolden the font, and specifying a bold face and a plain527* style does not lighten the font.528* <p>529* If no face for the requested style can be found, the font system530* may apply algorithmic styling to achieve the desired style.531* For example, if <code>ITALIC</code> is requested, but no italic532* face is available, glyphs from the plain face may be algorithmically533* obliqued (slanted).534* <p>535* Font name lookup is case insensitive, using the case folding536* rules of the US locale.537* <p>538* If the <code>name</code> parameter represents something other than a539* logical font, i.e. is interpreted as a physical font face or family, and540* this cannot be mapped by the implementation to a physical font or a541* compatible alternative, then the font system will map the Font542* instance to "Dialog", such that for example, the family as reported543* by {@link #getFamily() getFamily} will be "Dialog".544* <p>545*546* @param name the font name. This can be a font face name or a font547* family name, and may represent either a logical font or a physical548* font found in this {@code GraphicsEnvironment}.549* The family names for logical fonts are: Dialog, DialogInput,550* Monospaced, Serif, or SansSerif. Pre-defined String constants exist551* for all of these names, for example, {@code DIALOG}. If {@code name} is552* {@code null}, the <em>logical font name</em> of the new553* {@code Font} as returned by {@code getName()} is set to554* the name "Default".555* @param style the style constant for the {@code Font}556* The style argument is an integer bitmask that may557* be {@code PLAIN}, or a bitwise union of {@code BOLD} and/or558* {@code ITALIC} (for example, {@code ITALIC} or {@code BOLD|ITALIC}).559* If the style argument does not conform to one of the expected560* integer bitmasks then the style is set to {@code PLAIN}.561* @param size the point size of the {@code Font}562* @see GraphicsEnvironment#getAllFonts563* @see GraphicsEnvironment#getAvailableFontFamilyNames564* @since JDK1.0565*/566public Font(String name, int style, int size) {567this.name = (name != null) ? name : "Default";568this.style = (style & ~0x03) == 0 ? style : 0;569this.size = size;570this.pointSize = size;571}572573private Font(String name, int style, float sizePts) {574this.name = (name != null) ? name : "Default";575this.style = (style & ~0x03) == 0 ? style : 0;576this.size = (int)(sizePts + 0.5);577this.pointSize = sizePts;578}579580/* This constructor is used by deriveFont when attributes is null */581private Font(String name, int style, float sizePts,582boolean created, Font2DHandle handle) {583this(name, style, sizePts);584this.createdFont = created;585/* Fonts created from a stream will use the same font2D instance586* as the parent.587* One exception is that if the derived font is requested to be588* in a different style, then also check if its a CompositeFont589* and if so build a new CompositeFont from components of that style.590* CompositeFonts can only be marked as "created" if they are used591* to add fall backs to a physical font. And non-composites are592* always from "Font.createFont()" and shouldn't get this treatment.593*/594if (created) {595if (handle.font2D instanceof CompositeFont &&596handle.font2D.getStyle() != style) {597FontManager fm = FontManagerFactory.getInstance();598this.font2DHandle = fm.getNewComposite(null, style, handle);599} else {600this.font2DHandle = handle;601}602}603}604605/* used to implement Font.createFont */606private Font(File fontFile, int fontFormat,607boolean isCopy, CreatedFontTracker tracker)608throws FontFormatException {609this.createdFont = true;610/* Font2D instances created by this method track their font file611* so that when the Font2D is GC'd it can also remove the file.612*/613FontManager fm = FontManagerFactory.getInstance();614this.font2DHandle = fm.createFont2D(fontFile, fontFormat, isCopy,615tracker).handle;616this.name = this.font2DHandle.font2D.getFontName(Locale.getDefault());617this.style = Font.PLAIN;618this.size = 1;619this.pointSize = 1f;620}621622/* This constructor is used when one font is derived from another.623* Fonts created from a stream will use the same font2D instance as the624* parent. They can be distinguished because the "created" argument625* will be "true". Since there is no way to recreate these fonts they626* need to have the handle to the underlying font2D passed in.627* "created" is also true when a special composite is referenced by the628* handle for essentially the same reasons.629* But when deriving a font in these cases two particular attributes630* need special attention: family/face and style.631* The "composites" in these cases need to be recreated with optimal632* fonts for the new values of family and style.633* For fonts created with createFont() these are treated differently.634* JDK can often synthesise a different style (bold from plain635* for example). For fonts created with "createFont" this is a reasonable636* solution but its also possible (although rare) to derive a font with a637* different family attribute. In this case JDK needs638* to break the tie with the original Font2D and find a new Font.639* The oldName and oldStyle are supplied so they can be compared with640* what the Font2D and the values. To speed things along :641* oldName == null will be interpreted as the name is unchanged.642* oldStyle = -1 will be interpreted as the style is unchanged.643* In these cases there is no need to interrogate "values".644*/645private Font(AttributeValues values, String oldName, int oldStyle,646boolean created, Font2DHandle handle) {647648this.createdFont = created;649if (created) {650this.font2DHandle = handle;651652String newName = null;653if (oldName != null) {654newName = values.getFamily();655if (oldName.equals(newName)) newName = null;656}657int newStyle = 0;658if (oldStyle == -1) {659newStyle = -1;660} else {661if (values.getWeight() >= 2f) newStyle = BOLD;662if (values.getPosture() >= .2f) newStyle |= ITALIC;663if (oldStyle == newStyle) newStyle = -1;664}665if (handle.font2D instanceof CompositeFont) {666if (newStyle != -1 || newName != null) {667FontManager fm = FontManagerFactory.getInstance();668this.font2DHandle =669fm.getNewComposite(newName, newStyle, handle);670}671} else if (newName != null) {672this.createdFont = false;673this.font2DHandle = null;674}675}676initFromValues(values);677}678679/**680* Creates a new <code>Font</code> with the specified attributes.681* Only keys defined in {@link java.awt.font.TextAttribute TextAttribute}682* are recognized. In addition the FONT attribute is683* not recognized by this constructor684* (see {@link #getAvailableAttributes}). Only attributes that have685* values of valid types will affect the new <code>Font</code>.686* <p>687* If <code>attributes</code> is <code>null</code>, a new688* <code>Font</code> is initialized with default values.689* @see java.awt.font.TextAttribute690* @param attributes the attributes to assign to the new691* <code>Font</code>, or <code>null</code>692*/693public Font(Map<? extends Attribute, ?> attributes) {694initFromValues(AttributeValues.fromMap(attributes, RECOGNIZED_MASK));695}696697/**698* Creates a new <code>Font</code> from the specified <code>font</code>.699* This constructor is intended for use by subclasses.700* @param font from which to create this <code>Font</code>.701* @throws NullPointerException if <code>font</code> is null702* @since 1.6703*/704protected Font(Font font) {705if (font.values != null) {706initFromValues(font.getAttributeValues().clone());707} else {708this.name = font.name;709this.style = font.style;710this.size = font.size;711this.pointSize = font.pointSize;712}713this.font2DHandle = font.font2DHandle;714this.createdFont = font.createdFont;715}716717/**718* Font recognizes all attributes except FONT.719*/720private static final int RECOGNIZED_MASK = AttributeValues.MASK_ALL721& ~AttributeValues.getMask(EFONT);722723/**724* These attributes are considered primary by the FONT attribute.725*/726private static final int PRIMARY_MASK =727AttributeValues.getMask(EFAMILY, EWEIGHT, EWIDTH, EPOSTURE, ESIZE,728ETRANSFORM, ESUPERSCRIPT, ETRACKING);729730/**731* These attributes are considered secondary by the FONT attribute.732*/733private static final int SECONDARY_MASK =734RECOGNIZED_MASK & ~PRIMARY_MASK;735736/**737* These attributes are handled by layout.738*/739private static final int LAYOUT_MASK =740AttributeValues.getMask(ECHAR_REPLACEMENT, EFOREGROUND, EBACKGROUND,741EUNDERLINE, ESTRIKETHROUGH, ERUN_DIRECTION,742EBIDI_EMBEDDING, EJUSTIFICATION,743EINPUT_METHOD_HIGHLIGHT, EINPUT_METHOD_UNDERLINE,744ESWAP_COLORS, ENUMERIC_SHAPING, EKERNING,745ELIGATURES, ETRACKING, ESUPERSCRIPT);746747private static final int EXTRA_MASK =748AttributeValues.getMask(ETRANSFORM, ESUPERSCRIPT, EWIDTH);749750/**751* Initialize the standard Font fields from the values object.752*/753private void initFromValues(AttributeValues values) {754this.values = values;755values.defineAll(PRIMARY_MASK); // for 1.5 streaming compatibility756757this.name = values.getFamily();758this.pointSize = values.getSize();759this.size = (int)(values.getSize() + 0.5);760if (values.getWeight() >= 2f) this.style |= BOLD; // not == 2f761if (values.getPosture() >= .2f) this.style |= ITALIC; // not == .2f762763this.nonIdentityTx = values.anyNonDefault(EXTRA_MASK);764this.hasLayoutAttributes = values.anyNonDefault(LAYOUT_MASK);765}766767/**768* Returns a <code>Font</code> appropriate to the attributes.769* If <code>attributes</code>contains a <code>FONT</code> attribute770* with a valid <code>Font</code> as its value, it will be771* merged with any remaining attributes. See772* {@link java.awt.font.TextAttribute#FONT} for more773* information.774*775* @param attributes the attributes to assign to the new776* <code>Font</code>777* @return a new <code>Font</code> created with the specified778* attributes779* @throws NullPointerException if <code>attributes</code> is null.780* @since 1.2781* @see java.awt.font.TextAttribute782*/783public static Font getFont(Map<? extends Attribute, ?> attributes) {784// optimize for two cases:785// 1) FONT attribute, and nothing else786// 2) attributes, but no FONT787788// avoid turning the attributemap into a regular map for no reason789if (attributes instanceof AttributeMap &&790((AttributeMap)attributes).getValues() != null) {791AttributeValues values = ((AttributeMap)attributes).getValues();792if (values.isNonDefault(EFONT)) {793Font font = values.getFont();794if (!values.anyDefined(SECONDARY_MASK)) {795return font;796}797// merge798values = font.getAttributeValues().clone();799values.merge(attributes, SECONDARY_MASK);800return new Font(values, font.name, font.style,801font.createdFont, font.font2DHandle);802}803return new Font(attributes);804}805806Font font = (Font)attributes.get(TextAttribute.FONT);807if (font != null) {808if (attributes.size() > 1) { // oh well, check for anything else809AttributeValues values = font.getAttributeValues().clone();810values.merge(attributes, SECONDARY_MASK);811return new Font(values, font.name, font.style,812font.createdFont, font.font2DHandle);813}814815return font;816}817818return new Font(attributes);819}820821/**822* Used with the byte count tracker for fonts created from streams.823* If a thread can create temp files anyway, no point in counting824* font bytes.825*/826private static boolean hasTempPermission() {827828if (System.getSecurityManager() == null) {829return true;830}831File f = null;832boolean hasPerm = false;833try {834f = Files.createTempFile("+~JT", ".tmp").toFile();835f.delete();836f = null;837hasPerm = true;838} catch (Throwable t) {839/* inc. any kind of SecurityException */840}841return hasPerm;842}843844/**845* Returns a new <code>Font</code> using the specified font type846* and input data. The new <code>Font</code> is847* created with a point size of 1 and style {@link #PLAIN PLAIN}.848* This base font can then be used with the <code>deriveFont</code>849* methods in this class to derive new <code>Font</code> objects with850* varying sizes, styles, transforms and font features. This851* method does not close the {@link InputStream}.852* <p>853* To make the <code>Font</code> available to Font constructors the854* returned <code>Font</code> must be registered in the855* <code>GraphicsEnviroment</code> by calling856* {@link GraphicsEnvironment#registerFont(Font) registerFont(Font)}.857* @param fontFormat the type of the <code>Font</code>, which is858* {@link #TRUETYPE_FONT TRUETYPE_FONT} if a TrueType resource is specified.859* or {@link #TYPE1_FONT TYPE1_FONT} if a Type 1 resource is specified.860* @param fontStream an <code>InputStream</code> object representing the861* input data for the font.862* @return a new <code>Font</code> created with the specified font type.863* @throws IllegalArgumentException if <code>fontFormat</code> is not864* <code>TRUETYPE_FONT</code>or<code>TYPE1_FONT</code>.865* @throws FontFormatException if the <code>fontStream</code> data does866* not contain the required font tables for the specified format.867* @throws IOException if the <code>fontStream</code>868* cannot be completely read.869* @see GraphicsEnvironment#registerFont(Font)870* @since 1.3871*/872public static Font createFont(int fontFormat, InputStream fontStream)873throws java.awt.FontFormatException, java.io.IOException {874875if (hasTempPermission()) {876return createFont0(fontFormat, fontStream, null);877}878879// Otherwise, be extra conscious of pending temp file creation and880// resourcefully handle the temp file resources, among other things.881CreatedFontTracker tracker = CreatedFontTracker.getTracker();882boolean acquired = false;883try {884acquired = tracker.acquirePermit();885if (!acquired) {886throw new IOException("Timed out waiting for resources.");887}888return createFont0(fontFormat, fontStream, tracker);889} catch (InterruptedException e) {890throw new IOException("Problem reading font data.");891} finally {892if (acquired) {893tracker.releasePermit();894}895}896}897898private static Font createFont0(int fontFormat, InputStream fontStream,899CreatedFontTracker tracker)900throws java.awt.FontFormatException, java.io.IOException {901902if (fontFormat != Font.TRUETYPE_FONT &&903fontFormat != Font.TYPE1_FONT) {904throw new IllegalArgumentException ("font format not recognized");905}906boolean copiedFontData = false;907try {908final File tFile = AccessController.doPrivileged(909new PrivilegedExceptionAction<File>() {910public File run() throws IOException {911return Files.createTempFile("+~JF", ".tmp").toFile();912}913}914);915if (tracker != null) {916tracker.add(tFile);917}918919int totalSize = 0;920try {921final OutputStream outStream =922AccessController.doPrivileged(923new PrivilegedExceptionAction<OutputStream>() {924public OutputStream run() throws IOException {925return new FileOutputStream(tFile);926}927}928);929if (tracker != null) {930tracker.set(tFile, outStream);931}932try {933byte[] buf = new byte[8192];934for (;;) {935int bytesRead = fontStream.read(buf);936if (bytesRead < 0) {937break;938}939if (tracker != null) {940if (totalSize+bytesRead > CreatedFontTracker.MAX_FILE_SIZE) {941throw new IOException("File too big.");942}943if (totalSize+tracker.getNumBytes() >944CreatedFontTracker.MAX_TOTAL_BYTES)945{946throw new IOException("Total files too big.");947}948totalSize += bytesRead;949tracker.addBytes(bytesRead);950}951outStream.write(buf, 0, bytesRead);952}953/* don't close the input stream */954} finally {955outStream.close();956}957/* After all references to a Font2D are dropped, the file958* will be removed. To support long-lived AppContexts,959* we need to then decrement the byte count by the size960* of the file.961* If the data isn't a valid font, the implementation will962* delete the tmp file and decrement the byte count963* in the tracker object before returning from the964* constructor, so we can set 'copiedFontData' to true here965* without waiting for the results of that constructor.966*/967copiedFontData = true;968Font font = new Font(tFile, fontFormat, true, tracker);969return font;970} finally {971if (tracker != null) {972tracker.remove(tFile);973}974if (!copiedFontData) {975if (tracker != null) {976tracker.subBytes(totalSize);977}978AccessController.doPrivileged(979new PrivilegedExceptionAction<Void>() {980public Void run() {981tFile.delete();982return null;983}984}985);986}987}988} catch (Throwable t) {989if (t instanceof FontFormatException) {990throw (FontFormatException)t;991}992if (t instanceof IOException) {993throw (IOException)t;994}995Throwable cause = t.getCause();996if (cause instanceof FontFormatException) {997throw (FontFormatException)cause;998}999throw new IOException("Problem reading font data.");1000}1001}10021003/**1004* Returns a new <code>Font</code> using the specified font type1005* and the specified font file. The new <code>Font</code> is1006* created with a point size of 1 and style {@link #PLAIN PLAIN}.1007* This base font can then be used with the <code>deriveFont</code>1008* methods in this class to derive new <code>Font</code> objects with1009* varying sizes, styles, transforms and font features.1010* @param fontFormat the type of the <code>Font</code>, which is1011* {@link #TRUETYPE_FONT TRUETYPE_FONT} if a TrueType resource is1012* specified or {@link #TYPE1_FONT TYPE1_FONT} if a Type 1 resource is1013* specified.1014* So long as the returned font, or its derived fonts are referenced1015* the implementation may continue to access <code>fontFile</code>1016* to retrieve font data. Thus the results are undefined if the file1017* is changed, or becomes inaccessible.1018* <p>1019* To make the <code>Font</code> available to Font constructors the1020* returned <code>Font</code> must be registered in the1021* <code>GraphicsEnviroment</code> by calling1022* {@link GraphicsEnvironment#registerFont(Font) registerFont(Font)}.1023* @param fontFile a <code>File</code> object representing the1024* input data for the font.1025* @return a new <code>Font</code> created with the specified font type.1026* @throws IllegalArgumentException if <code>fontFormat</code> is not1027* <code>TRUETYPE_FONT</code>or<code>TYPE1_FONT</code>.1028* @throws NullPointerException if <code>fontFile</code> is null.1029* @throws IOException if the <code>fontFile</code> cannot be read.1030* @throws FontFormatException if <code>fontFile</code> does1031* not contain the required font tables for the specified format.1032* @throws SecurityException if the executing code does not have1033* permission to read from the file.1034* @see GraphicsEnvironment#registerFont(Font)1035* @since 1.51036*/1037public static Font createFont(int fontFormat, File fontFile)1038throws java.awt.FontFormatException, java.io.IOException {10391040fontFile = new File(fontFile.getPath());10411042if (fontFormat != Font.TRUETYPE_FONT &&1043fontFormat != Font.TYPE1_FONT) {1044throw new IllegalArgumentException ("font format not recognized");1045}1046SecurityManager sm = System.getSecurityManager();1047if (sm != null) {1048FilePermission filePermission =1049new FilePermission(fontFile.getPath(), "read");1050sm.checkPermission(filePermission);1051}1052if (!fontFile.canRead()) {1053throw new IOException("Can't read " + fontFile);1054}1055return new Font(fontFile, fontFormat, false, null);1056}10571058/**1059* Returns a copy of the transform associated with this1060* <code>Font</code>. This transform is not necessarily the one1061* used to construct the font. If the font has algorithmic1062* superscripting or width adjustment, this will be incorporated1063* into the returned <code>AffineTransform</code>.1064* <p>1065* Typically, fonts will not be transformed. Clients generally1066* should call {@link #isTransformed} first, and only call this1067* method if <code>isTransformed</code> returns true.1068*1069* @return an {@link AffineTransform} object representing the1070* transform attribute of this <code>Font</code> object.1071*/1072public AffineTransform getTransform() {1073/* The most common case is the identity transform. Most callers1074* should call isTransformed() first, to decide if they need to1075* get the transform, but some may not. Here we check to see1076* if we have a nonidentity transform, and only do the work to1077* fetch and/or compute it if so, otherwise we return a new1078* identity transform.1079*1080* Note that the transform is _not_ necessarily the same as1081* the transform passed in as an Attribute in a Map, as the1082* transform returned will also reflect the effects of WIDTH and1083* SUPERSCRIPT attributes. Clients who want the actual transform1084* need to call getRequestedAttributes.1085*/1086if (nonIdentityTx) {1087AttributeValues values = getAttributeValues();10881089AffineTransform at = values.isNonDefault(ETRANSFORM)1090? new AffineTransform(values.getTransform())1091: new AffineTransform();10921093if (values.getSuperscript() != 0) {1094// can't get ascent and descent here, recursive call to this fn,1095// so use pointsize1096// let users combine super- and sub-scripting10971098int superscript = values.getSuperscript();10991100double trans = 0;1101int n = 0;1102boolean up = superscript > 0;1103int sign = up ? -1 : 1;1104int ss = up ? superscript : -superscript;11051106while ((ss & 7) > n) {1107int newn = ss & 7;1108trans += sign * (ssinfo[newn] - ssinfo[n]);1109ss >>= 3;1110sign = -sign;1111n = newn;1112}1113trans *= pointSize;1114double scale = Math.pow(2./3., n);11151116at.preConcatenate(AffineTransform.getTranslateInstance(0, trans));1117at.scale(scale, scale);11181119// note on placement and italics1120// We preconcatenate the transform because we don't want to translate along1121// the italic angle, but purely perpendicular to the baseline. While this1122// looks ok for superscripts, it can lead subscripts to stack on each other1123// and bring the following text too close. The way we deal with potential1124// collisions that can occur in the case of italics is by adjusting the1125// horizontal spacing of the adjacent glyphvectors. Examine the italic1126// angle of both vectors, if one is non-zero, compute the minimum ascent1127// and descent, and then the x position at each for each vector along its1128// italic angle starting from its (offset) baseline. Compute the difference1129// between the x positions and use the maximum difference to adjust the1130// position of the right gv.1131}11321133if (values.isNonDefault(EWIDTH)) {1134at.scale(values.getWidth(), 1f);1135}11361137return at;1138}11391140return new AffineTransform();1141}11421143// x = r^0 + r^1 + r^2... r^n1144// rx = r^1 + r^2 + r^3... r^(n+1)1145// x - rx = r^0 - r^(n+1)1146// x (1 - r) = r^0 - r^(n+1)1147// x = (r^0 - r^(n+1)) / (1 - r)1148// x = (1 - r^(n+1)) / (1 - r)11491150// scale ratio is 2/31151// trans = 1/2 of ascent * x1152// assume ascent is 3/4 of point size11531154private static final float[] ssinfo = {11550.0f,11560.375f,11570.625f,11580.7916667f,11590.9027778f,11600.9768519f,11611.0262346f,11621.0591564f,1163};11641165/**1166* Returns the family name of this <code>Font</code>.1167*1168* <p>The family name of a font is font specific. Two fonts such as1169* Helvetica Italic and Helvetica Bold have the same family name,1170* <i>Helvetica</i>, whereas their font face names are1171* <i>Helvetica Bold</i> and <i>Helvetica Italic</i>. The list of1172* available family names may be obtained by using the1173* {@link GraphicsEnvironment#getAvailableFontFamilyNames()} method.1174*1175* <p>Use <code>getName</code> to get the logical name of the font.1176* Use <code>getFontName</code> to get the font face name of the font.1177* @return a <code>String</code> that is the family name of this1178* <code>Font</code>.1179*1180* @see #getName1181* @see #getFontName1182* @since JDK1.11183*/1184public String getFamily() {1185return getFamily_NoClientCode();1186}1187// NOTE: This method is called by privileged threads.1188// We implement this functionality in a package-private1189// method to insure that it cannot be overridden by client1190// subclasses.1191// DO NOT INVOKE CLIENT CODE ON THIS THREAD!1192final String getFamily_NoClientCode() {1193return getFamily(Locale.getDefault());1194}11951196/**1197* Returns the family name of this <code>Font</code>, localized for1198* the specified locale.1199*1200* <p>The family name of a font is font specific. Two fonts such as1201* Helvetica Italic and Helvetica Bold have the same family name,1202* <i>Helvetica</i>, whereas their font face names are1203* <i>Helvetica Bold</i> and <i>Helvetica Italic</i>. The list of1204* available family names may be obtained by using the1205* {@link GraphicsEnvironment#getAvailableFontFamilyNames()} method.1206*1207* <p>Use <code>getFontName</code> to get the font face name of the font.1208* @param l locale for which to get the family name1209* @return a <code>String</code> representing the family name of the1210* font, localized for the specified locale.1211* @see #getFontName1212* @see java.util.Locale1213* @since 1.21214*/1215public String getFamily(Locale l) {1216if (l == null) {1217throw new NullPointerException("null locale doesn't mean default");1218}1219return getFont2D().getFamilyName(l);1220}12211222/**1223* Returns the postscript name of this <code>Font</code>.1224* Use <code>getFamily</code> to get the family name of the font.1225* Use <code>getFontName</code> to get the font face name of the font.1226* @return a <code>String</code> representing the postscript name of1227* this <code>Font</code>.1228* @since 1.21229*/1230public String getPSName() {1231return getFont2D().getPostscriptName();1232}12331234/**1235* Returns the logical name of this <code>Font</code>.1236* Use <code>getFamily</code> to get the family name of the font.1237* Use <code>getFontName</code> to get the font face name of the font.1238* @return a <code>String</code> representing the logical name of1239* this <code>Font</code>.1240* @see #getFamily1241* @see #getFontName1242* @since JDK1.01243*/1244public String getName() {1245return name;1246}12471248/**1249* Returns the font face name of this <code>Font</code>. For example,1250* Helvetica Bold could be returned as a font face name.1251* Use <code>getFamily</code> to get the family name of the font.1252* Use <code>getName</code> to get the logical name of the font.1253* @return a <code>String</code> representing the font face name of1254* this <code>Font</code>.1255* @see #getFamily1256* @see #getName1257* @since 1.21258*/1259public String getFontName() {1260return getFontName(Locale.getDefault());1261}12621263/**1264* Returns the font face name of the <code>Font</code>, localized1265* for the specified locale. For example, Helvetica Fett could be1266* returned as the font face name.1267* Use <code>getFamily</code> to get the family name of the font.1268* @param l a locale for which to get the font face name1269* @return a <code>String</code> representing the font face name,1270* localized for the specified locale.1271* @see #getFamily1272* @see java.util.Locale1273*/1274public String getFontName(Locale l) {1275if (l == null) {1276throw new NullPointerException("null locale doesn't mean default");1277}1278return getFont2D().getFontName(l);1279}12801281/**1282* Returns the style of this <code>Font</code>. The style can be1283* PLAIN, BOLD, ITALIC, or BOLD+ITALIC.1284* @return the style of this <code>Font</code>1285* @see #isPlain1286* @see #isBold1287* @see #isItalic1288* @since JDK1.01289*/1290public int getStyle() {1291return style;1292}12931294/**1295* Returns the point size of this <code>Font</code>, rounded to1296* an integer.1297* Most users are familiar with the idea of using <i>point size</i> to1298* specify the size of glyphs in a font. This point size defines a1299* measurement between the baseline of one line to the baseline of the1300* following line in a single spaced text document. The point size is1301* based on <i>typographic points</i>, approximately 1/72 of an inch.1302* <p>1303* The Java(tm)2D API adopts the convention that one point is1304* equivalent to one unit in user coordinates. When using a1305* normalized transform for converting user space coordinates to1306* device space coordinates 72 user1307* space units equal 1 inch in device space. In this case one point1308* is 1/72 of an inch.1309* @return the point size of this <code>Font</code> in 1/72 of an1310* inch units.1311* @see #getSize2D1312* @see GraphicsConfiguration#getDefaultTransform1313* @see GraphicsConfiguration#getNormalizingTransform1314* @since JDK1.01315*/1316public int getSize() {1317return size;1318}13191320/**1321* Returns the point size of this <code>Font</code> in1322* <code>float</code> value.1323* @return the point size of this <code>Font</code> as a1324* <code>float</code> value.1325* @see #getSize1326* @since 1.21327*/1328public float getSize2D() {1329return pointSize;1330}13311332/**1333* Indicates whether or not this <code>Font</code> object's style is1334* PLAIN.1335* @return <code>true</code> if this <code>Font</code> has a1336* PLAIN style;1337* <code>false</code> otherwise.1338* @see java.awt.Font#getStyle1339* @since JDK1.01340*/1341public boolean isPlain() {1342return style == 0;1343}13441345/**1346* Indicates whether or not this <code>Font</code> object's style is1347* BOLD.1348* @return <code>true</code> if this <code>Font</code> object's1349* style is BOLD;1350* <code>false</code> otherwise.1351* @see java.awt.Font#getStyle1352* @since JDK1.01353*/1354public boolean isBold() {1355return (style & BOLD) != 0;1356}13571358/**1359* Indicates whether or not this <code>Font</code> object's style is1360* ITALIC.1361* @return <code>true</code> if this <code>Font</code> object's1362* style is ITALIC;1363* <code>false</code> otherwise.1364* @see java.awt.Font#getStyle1365* @since JDK1.01366*/1367public boolean isItalic() {1368return (style & ITALIC) != 0;1369}13701371/**1372* Indicates whether or not this <code>Font</code> object has a1373* transform that affects its size in addition to the Size1374* attribute.1375* @return <code>true</code> if this <code>Font</code> object1376* has a non-identity AffineTransform attribute.1377* <code>false</code> otherwise.1378* @see java.awt.Font#getTransform1379* @since 1.41380*/1381public boolean isTransformed() {1382return nonIdentityTx;1383}13841385/**1386* Return true if this Font contains attributes that require extra1387* layout processing.1388* @return true if the font has layout attributes1389* @since 1.61390*/1391public boolean hasLayoutAttributes() {1392return hasLayoutAttributes;1393}13941395/**1396* Returns a <code>Font</code> object from the system properties list.1397* <code>nm</code> is treated as the name of a system property to be1398* obtained. The <code>String</code> value of this property is then1399* interpreted as a <code>Font</code> object according to the1400* specification of <code>Font.decode(String)</code>1401* If the specified property is not found, or the executing code does1402* not have permission to read the property, null is returned instead.1403*1404* @param nm the property name1405* @return a <code>Font</code> object that the property name1406* describes, or null if no such property exists.1407* @throws NullPointerException if nm is null.1408* @since 1.21409* @see #decode(String)1410*/1411public static Font getFont(String nm) {1412return getFont(nm, null);1413}14141415/**1416* Returns the <code>Font</code> that the <code>str</code>1417* argument describes.1418* To ensure that this method returns the desired Font,1419* format the <code>str</code> parameter in1420* one of these ways1421*1422* <ul>1423* <li><em>fontname-style-pointsize</em>1424* <li><em>fontname-pointsize</em>1425* <li><em>fontname-style</em>1426* <li><em>fontname</em>1427* <li><em>fontname style pointsize</em>1428* <li><em>fontname pointsize</em>1429* <li><em>fontname style</em>1430* <li><em>fontname</em>1431* </ul>1432* in which <i>style</i> is one of the four1433* case-insensitive strings:1434* <code>"PLAIN"</code>, <code>"BOLD"</code>, <code>"BOLDITALIC"</code>, or1435* <code>"ITALIC"</code>, and pointsize is a positive decimal integer1436* representation of the point size.1437* For example, if you want a font that is Arial, bold, with1438* a point size of 18, you would call this method with:1439* "Arial-BOLD-18".1440* This is equivalent to calling the Font constructor :1441* <code>new Font("Arial", Font.BOLD, 18);</code>1442* and the values are interpreted as specified by that constructor.1443* <p>1444* A valid trailing decimal field is always interpreted as the pointsize.1445* Therefore a fontname containing a trailing decimal value should not1446* be used in the fontname only form.1447* <p>1448* If a style name field is not one of the valid style strings, it is1449* interpreted as part of the font name, and the default style is used.1450* <p>1451* Only one of ' ' or '-' may be used to separate fields in the input.1452* The identified separator is the one closest to the end of the string1453* which separates a valid pointsize, or a valid style name from1454* the rest of the string.1455* Null (empty) pointsize and style fields are treated1456* as valid fields with the default value for that field.1457*<p>1458* Some font names may include the separator characters ' ' or '-'.1459* If <code>str</code> is not formed with 3 components, e.g. such that1460* <code>style</code> or <code>pointsize</code> fields are not present in1461* <code>str</code>, and <code>fontname</code> also contains a1462* character determined to be the separator character1463* then these characters where they appear as intended to be part of1464* <code>fontname</code> may instead be interpreted as separators1465* so the font name may not be properly recognised.1466*1467* <p>1468* The default size is 12 and the default style is PLAIN.1469* If <code>str</code> does not specify a valid size, the returned1470* <code>Font</code> has a size of 12. If <code>str</code> does not1471* specify a valid style, the returned Font has a style of PLAIN.1472* If you do not specify a valid font name in1473* the <code>str</code> argument, this method will return1474* a font with the family name "Dialog".1475* To determine what font family names are available on1476* your system, use the1477* {@link GraphicsEnvironment#getAvailableFontFamilyNames()} method.1478* If <code>str</code> is <code>null</code>, a new <code>Font</code>1479* is returned with the family name "Dialog", a size of 12 and a1480* PLAIN style.1481* @param str the name of the font, or <code>null</code>1482* @return the <code>Font</code> object that <code>str</code>1483* describes, or a new default <code>Font</code> if1484* <code>str</code> is <code>null</code>.1485* @see #getFamily1486* @since JDK1.11487*/1488public static Font decode(String str) {1489String fontName = str;1490String styleName = "";1491int fontSize = 12;1492int fontStyle = Font.PLAIN;14931494if (str == null) {1495return new Font(DIALOG, fontStyle, fontSize);1496}14971498int lastHyphen = str.lastIndexOf('-');1499int lastSpace = str.lastIndexOf(' ');1500char sepChar = (lastHyphen > lastSpace) ? '-' : ' ';1501int sizeIndex = str.lastIndexOf(sepChar);1502int styleIndex = str.lastIndexOf(sepChar, sizeIndex-1);1503int strlen = str.length();15041505if (sizeIndex > 0 && sizeIndex+1 < strlen) {1506try {1507fontSize =1508Integer.valueOf(str.substring(sizeIndex+1)).intValue();1509if (fontSize <= 0) {1510fontSize = 12;1511}1512} catch (NumberFormatException e) {1513/* It wasn't a valid size, if we didn't also find the1514* start of the style string perhaps this is the style */1515styleIndex = sizeIndex;1516sizeIndex = strlen;1517if (str.charAt(sizeIndex-1) == sepChar) {1518sizeIndex--;1519}1520}1521}15221523if (styleIndex >= 0 && styleIndex+1 < strlen) {1524styleName = str.substring(styleIndex+1, sizeIndex);1525styleName = styleName.toLowerCase(Locale.ENGLISH);1526if (styleName.equals("bolditalic")) {1527fontStyle = Font.BOLD | Font.ITALIC;1528} else if (styleName.equals("italic")) {1529fontStyle = Font.ITALIC;1530} else if (styleName.equals("bold")) {1531fontStyle = Font.BOLD;1532} else if (styleName.equals("plain")) {1533fontStyle = Font.PLAIN;1534} else {1535/* this string isn't any of the expected styles, so1536* assume its part of the font name1537*/1538styleIndex = sizeIndex;1539if (str.charAt(styleIndex-1) == sepChar) {1540styleIndex--;1541}1542}1543fontName = str.substring(0, styleIndex);15441545} else {1546int fontEnd = strlen;1547if (styleIndex > 0) {1548fontEnd = styleIndex;1549} else if (sizeIndex > 0) {1550fontEnd = sizeIndex;1551}1552if (fontEnd > 0 && str.charAt(fontEnd-1) == sepChar) {1553fontEnd--;1554}1555fontName = str.substring(0, fontEnd);1556}15571558return new Font(fontName, fontStyle, fontSize);1559}15601561/**1562* Gets the specified <code>Font</code> from the system properties1563* list. As in the <code>getProperty</code> method of1564* <code>System</code>, the first1565* argument is treated as the name of a system property to be1566* obtained. The <code>String</code> value of this property is then1567* interpreted as a <code>Font</code> object.1568* <p>1569* The property value should be one of the forms accepted by1570* <code>Font.decode(String)</code>1571* If the specified property is not found, or the executing code does not1572* have permission to read the property, the <code>font</code>1573* argument is returned instead.1574* @param nm the case-insensitive property name1575* @param font a default <code>Font</code> to return if property1576* <code>nm</code> is not defined1577* @return the <code>Font</code> value of the property.1578* @throws NullPointerException if nm is null.1579* @see #decode(String)1580*/1581public static Font getFont(String nm, Font font) {1582String str = null;1583try {1584str =System.getProperty(nm);1585} catch(SecurityException e) {1586}1587if (str == null) {1588return font;1589}1590return decode ( str );1591}15921593transient int hash;1594/**1595* Returns a hashcode for this <code>Font</code>.1596* @return a hashcode value for this <code>Font</code>.1597* @since JDK1.01598*/1599public int hashCode() {1600if (hash == 0) {1601hash = name.hashCode() ^ style ^ size;1602/* It is possible many fonts differ only in transform.1603* So include the transform in the hash calculation.1604* nonIdentityTx is set whenever there is a transform in1605* 'values'. The tests for null are required because it can1606* also be set for other reasons.1607*/1608if (nonIdentityTx &&1609values != null && values.getTransform() != null) {1610hash ^= values.getTransform().hashCode();1611}1612}1613return hash;1614}16151616/**1617* Compares this <code>Font</code> object to the specified1618* <code>Object</code>.1619* @param obj the <code>Object</code> to compare1620* @return <code>true</code> if the objects are the same1621* or if the argument is a <code>Font</code> object1622* describing the same font as this object;1623* <code>false</code> otherwise.1624* @since JDK1.01625*/1626public boolean equals(Object obj) {1627if (obj == this) {1628return true;1629}16301631if (obj != null) {1632try {1633Font font = (Font)obj;1634if (size == font.size &&1635style == font.style &&1636nonIdentityTx == font.nonIdentityTx &&1637hasLayoutAttributes == font.hasLayoutAttributes &&1638pointSize == font.pointSize &&1639name.equals(font.name)) {16401641/* 'values' is usually initialized lazily, except when1642* the font is constructed from a Map, or derived using1643* a Map or other values. So if only one font has1644* the field initialized we need to initialize it in1645* the other instance and compare.1646*/1647if (values == null) {1648if (font.values == null) {1649return true;1650} else {1651return getAttributeValues().equals(font.values);1652}1653} else {1654return values.equals(font.getAttributeValues());1655}1656}1657}1658catch (ClassCastException e) {1659}1660}1661return false;1662}16631664/**1665* Converts this <code>Font</code> object to a <code>String</code>1666* representation.1667* @return a <code>String</code> representation of this1668* <code>Font</code> object.1669* @since JDK1.01670*/1671// NOTE: This method may be called by privileged threads.1672// DO NOT INVOKE CLIENT CODE ON THIS THREAD!1673public String toString() {1674String strStyle;16751676if (isBold()) {1677strStyle = isItalic() ? "bolditalic" : "bold";1678} else {1679strStyle = isItalic() ? "italic" : "plain";1680}16811682return getClass().getName() + "[family=" + getFamily() + ",name=" + name + ",style=" +1683strStyle + ",size=" + size + "]";1684} // toString()168516861687/** Serialization support. A <code>readObject</code>1688* method is neccessary because the constructor creates1689* the font's peer, and we can't serialize the peer.1690* Similarly the computed font "family" may be different1691* at <code>readObject</code> time than at1692* <code>writeObject</code> time. An integer version is1693* written so that future versions of this class will be1694* able to recognize serialized output from this one.1695*/1696/**1697* The <code>Font</code> Serializable Data Form.1698*1699* @serial1700*/1701private int fontSerializedDataVersion = 1;17021703/**1704* Writes default serializable fields to a stream.1705*1706* @param s the <code>ObjectOutputStream</code> to write1707* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)1708* @see #readObject(java.io.ObjectInputStream)1709*/1710private void writeObject(java.io.ObjectOutputStream s)1711throws java.lang.ClassNotFoundException,1712java.io.IOException1713{1714if (values != null) {1715synchronized(values) {1716// transient1717fRequestedAttributes = values.toSerializableHashtable();1718s.defaultWriteObject();1719fRequestedAttributes = null;1720}1721} else {1722s.defaultWriteObject();1723}1724}17251726/**1727* Reads the <code>ObjectInputStream</code>.1728* Unrecognized keys or values will be ignored.1729*1730* @param s the <code>ObjectInputStream</code> to read1731* @serial1732* @see #writeObject(java.io.ObjectOutputStream)1733*/1734private void readObject(java.io.ObjectInputStream s)1735throws java.lang.ClassNotFoundException,1736java.io.IOException1737{1738s.defaultReadObject();1739if (pointSize == 0) {1740pointSize = (float)size;1741}17421743// Handle fRequestedAttributes.1744// in 1.5, we always streamed out the font values plus1745// TRANSFORM, SUPERSCRIPT, and WIDTH, regardless of whether the1746// values were default or not. In 1.6 we only stream out1747// defined values. So, 1.6 streams in from a 1.5 stream,1748// it check each of these values and 'undefines' it if the1749// value is the default.17501751if (fRequestedAttributes != null) {1752try {1753values = getAttributeValues(); // init1754AttributeValues extras =1755AttributeValues.fromSerializableHashtable(fRequestedAttributes);1756if (!AttributeValues.is16Hashtable(fRequestedAttributes)) {1757extras.unsetDefault(); // if legacy stream, undefine these1758}1759values = getAttributeValues().merge(extras);1760this.nonIdentityTx = values.anyNonDefault(EXTRA_MASK);1761this.hasLayoutAttributes = values.anyNonDefault(LAYOUT_MASK);1762} catch (Throwable t) {1763throw new IOException(t);1764} finally {1765fRequestedAttributes = null; // don't need it any more1766}1767}1768}17691770/**1771* Returns the number of glyphs in this <code>Font</code>. Glyph codes1772* for this <code>Font</code> range from 0 to1773* <code>getNumGlyphs()</code> - 1.1774* @return the number of glyphs in this <code>Font</code>.1775* @since 1.21776*/1777public int getNumGlyphs() {1778return getFont2D().getNumGlyphs();1779}17801781/**1782* Returns the glyphCode which is used when this <code>Font</code>1783* does not have a glyph for a specified unicode code point.1784* @return the glyphCode of this <code>Font</code>.1785* @since 1.21786*/1787public int getMissingGlyphCode() {1788return getFont2D().getMissingGlyphCode();1789}17901791/**1792* Returns the baseline appropriate for displaying this character.1793* <p>1794* Large fonts can support different writing systems, and each system can1795* use a different baseline.1796* The character argument determines the writing system to use. Clients1797* should not assume all characters use the same baseline.1798*1799* @param c a character used to identify the writing system1800* @return the baseline appropriate for the specified character.1801* @see LineMetrics#getBaselineOffsets1802* @see #ROMAN_BASELINE1803* @see #CENTER_BASELINE1804* @see #HANGING_BASELINE1805* @since 1.21806*/1807public byte getBaselineFor(char c) {1808return getFont2D().getBaselineFor(c);1809}18101811/**1812* Returns a map of font attributes available in this1813* <code>Font</code>. Attributes include things like ligatures and1814* glyph substitution.1815* @return the attributes map of this <code>Font</code>.1816*/1817public Map<TextAttribute,?> getAttributes(){1818return new AttributeMap(getAttributeValues());1819}18201821/**1822* Returns the keys of all the attributes supported by this1823* <code>Font</code>. These attributes can be used to derive other1824* fonts.1825* @return an array containing the keys of all the attributes1826* supported by this <code>Font</code>.1827* @since 1.21828*/1829public Attribute[] getAvailableAttributes() {1830// FONT is not supported by Font18311832Attribute attributes[] = {1833TextAttribute.FAMILY,1834TextAttribute.WEIGHT,1835TextAttribute.WIDTH,1836TextAttribute.POSTURE,1837TextAttribute.SIZE,1838TextAttribute.TRANSFORM,1839TextAttribute.SUPERSCRIPT,1840TextAttribute.CHAR_REPLACEMENT,1841TextAttribute.FOREGROUND,1842TextAttribute.BACKGROUND,1843TextAttribute.UNDERLINE,1844TextAttribute.STRIKETHROUGH,1845TextAttribute.RUN_DIRECTION,1846TextAttribute.BIDI_EMBEDDING,1847TextAttribute.JUSTIFICATION,1848TextAttribute.INPUT_METHOD_HIGHLIGHT,1849TextAttribute.INPUT_METHOD_UNDERLINE,1850TextAttribute.SWAP_COLORS,1851TextAttribute.NUMERIC_SHAPING,1852TextAttribute.KERNING,1853TextAttribute.LIGATURES,1854TextAttribute.TRACKING,1855};18561857return attributes;1858}18591860/**1861* Creates a new <code>Font</code> object by replicating this1862* <code>Font</code> object and applying a new style and size.1863* @param style the style for the new <code>Font</code>1864* @param size the size for the new <code>Font</code>1865* @return a new <code>Font</code> object.1866* @since 1.21867*/1868public Font deriveFont(int style, float size){1869if (values == null) {1870return new Font(name, style, size, createdFont, font2DHandle);1871}1872AttributeValues newValues = getAttributeValues().clone();1873int oldStyle = (this.style != style) ? this.style : -1;1874applyStyle(style, newValues);1875newValues.setSize(size);1876return new Font(newValues, null, oldStyle, createdFont, font2DHandle);1877}18781879/**1880* Creates a new <code>Font</code> object by replicating this1881* <code>Font</code> object and applying a new style and transform.1882* @param style the style for the new <code>Font</code>1883* @param trans the <code>AffineTransform</code> associated with the1884* new <code>Font</code>1885* @return a new <code>Font</code> object.1886* @throws IllegalArgumentException if <code>trans</code> is1887* <code>null</code>1888* @since 1.21889*/1890public Font deriveFont(int style, AffineTransform trans){1891AttributeValues newValues = getAttributeValues().clone();1892int oldStyle = (this.style != style) ? this.style : -1;1893applyStyle(style, newValues);1894applyTransform(trans, newValues);1895return new Font(newValues, null, oldStyle, createdFont, font2DHandle);1896}18971898/**1899* Creates a new <code>Font</code> object by replicating the current1900* <code>Font</code> object and applying a new size to it.1901* @param size the size for the new <code>Font</code>.1902* @return a new <code>Font</code> object.1903* @since 1.21904*/1905public Font deriveFont(float size){1906if (values == null) {1907return new Font(name, style, size, createdFont, font2DHandle);1908}1909AttributeValues newValues = getAttributeValues().clone();1910newValues.setSize(size);1911return new Font(newValues, null, -1, createdFont, font2DHandle);1912}19131914/**1915* Creates a new <code>Font</code> object by replicating the current1916* <code>Font</code> object and applying a new transform to it.1917* @param trans the <code>AffineTransform</code> associated with the1918* new <code>Font</code>1919* @return a new <code>Font</code> object.1920* @throws IllegalArgumentException if <code>trans</code> is1921* <code>null</code>1922* @since 1.21923*/1924public Font deriveFont(AffineTransform trans){1925AttributeValues newValues = getAttributeValues().clone();1926applyTransform(trans, newValues);1927return new Font(newValues, null, -1, createdFont, font2DHandle);1928}19291930/**1931* Creates a new <code>Font</code> object by replicating the current1932* <code>Font</code> object and applying a new style to it.1933* @param style the style for the new <code>Font</code>1934* @return a new <code>Font</code> object.1935* @since 1.21936*/1937public Font deriveFont(int style){1938if (values == null) {1939return new Font(name, style, size, createdFont, font2DHandle);1940}1941AttributeValues newValues = getAttributeValues().clone();1942int oldStyle = (this.style != style) ? this.style : -1;1943applyStyle(style, newValues);1944return new Font(newValues, null, oldStyle, createdFont, font2DHandle);1945}19461947/**1948* Creates a new <code>Font</code> object by replicating the current1949* <code>Font</code> object and applying a new set of font attributes1950* to it.1951*1952* @param attributes a map of attributes enabled for the new1953* <code>Font</code>1954* @return a new <code>Font</code> object.1955* @since 1.21956*/1957public Font deriveFont(Map<? extends Attribute, ?> attributes) {1958if (attributes == null) {1959return this;1960}1961AttributeValues newValues = getAttributeValues().clone();1962newValues.merge(attributes, RECOGNIZED_MASK);19631964return new Font(newValues, name, style, createdFont, font2DHandle);1965}19661967/**1968* Checks if this <code>Font</code> has a glyph for the specified1969* character.1970*1971* <p> <b>Note:</b> This method cannot handle <a1972* href="../../java/lang/Character.html#supplementary"> supplementary1973* characters</a>. To support all Unicode characters, including1974* supplementary characters, use the {@link #canDisplay(int)}1975* method or <code>canDisplayUpTo</code> methods.1976*1977* @param c the character for which a glyph is needed1978* @return <code>true</code> if this <code>Font</code> has a glyph for this1979* character; <code>false</code> otherwise.1980* @since 1.21981*/1982public boolean canDisplay(char c){1983return getFont2D().canDisplay(c);1984}19851986/**1987* Checks if this <code>Font</code> has a glyph for the specified1988* character.1989*1990* @param codePoint the character (Unicode code point) for which a glyph1991* is needed.1992* @return <code>true</code> if this <code>Font</code> has a glyph for the1993* character; <code>false</code> otherwise.1994* @throws IllegalArgumentException if the code point is not a valid Unicode1995* code point.1996* @see Character#isValidCodePoint(int)1997* @since 1.51998*/1999public boolean canDisplay(int codePoint) {2000if (!Character.isValidCodePoint(codePoint)) {2001throw new IllegalArgumentException("invalid code point: " +2002Integer.toHexString(codePoint));2003}2004return getFont2D().canDisplay(codePoint);2005}20062007/**2008* Indicates whether or not this <code>Font</code> can display a2009* specified <code>String</code>. For strings with Unicode encoding,2010* it is important to know if a particular font can display the2011* string. This method returns an offset into the <code>String</code>2012* <code>str</code> which is the first character this2013* <code>Font</code> cannot display without using the missing glyph2014* code. If the <code>Font</code> can display all characters, -1 is2015* returned.2016* @param str a <code>String</code> object2017* @return an offset into <code>str</code> that points2018* to the first character in <code>str</code> that this2019* <code>Font</code> cannot display; or <code>-1</code> if2020* this <code>Font</code> can display all characters in2021* <code>str</code>.2022* @since 1.22023*/2024public int canDisplayUpTo(String str) {2025Font2D font2d = getFont2D();2026int len = str.length();2027for (int i = 0; i < len; i++) {2028char c = str.charAt(i);2029if (font2d.canDisplay(c)) {2030continue;2031}2032if (!Character.isHighSurrogate(c)) {2033return i;2034}2035if (!font2d.canDisplay(str.codePointAt(i))) {2036return i;2037}2038i++;2039}2040return -1;2041}20422043/**2044* Indicates whether or not this <code>Font</code> can display2045* the characters in the specified <code>text</code>2046* starting at <code>start</code> and ending at2047* <code>limit</code>. This method is a convenience overload.2048* @param text the specified array of <code>char</code> values2049* @param start the specified starting offset (in2050* <code>char</code>s) into the specified array of2051* <code>char</code> values2052* @param limit the specified ending offset (in2053* <code>char</code>s) into the specified array of2054* <code>char</code> values2055* @return an offset into <code>text</code> that points2056* to the first character in <code>text</code> that this2057* <code>Font</code> cannot display; or <code>-1</code> if2058* this <code>Font</code> can display all characters in2059* <code>text</code>.2060* @since 1.22061*/2062public int canDisplayUpTo(char[] text, int start, int limit) {2063Font2D font2d = getFont2D();2064for (int i = start; i < limit; i++) {2065char c = text[i];2066if (font2d.canDisplay(c)) {2067continue;2068}2069if (!Character.isHighSurrogate(c)) {2070return i;2071}2072if (!font2d.canDisplay(Character.codePointAt(text, i, limit))) {2073return i;2074}2075i++;2076}2077return -1;2078}20792080/**2081* Indicates whether or not this <code>Font</code> can display the2082* text specified by the <code>iter</code> starting at2083* <code>start</code> and ending at <code>limit</code>.2084*2085* @param iter a {@link CharacterIterator} object2086* @param start the specified starting offset into the specified2087* <code>CharacterIterator</code>.2088* @param limit the specified ending offset into the specified2089* <code>CharacterIterator</code>.2090* @return an offset into <code>iter</code> that points2091* to the first character in <code>iter</code> that this2092* <code>Font</code> cannot display; or <code>-1</code> if2093* this <code>Font</code> can display all characters in2094* <code>iter</code>.2095* @since 1.22096*/2097public int canDisplayUpTo(CharacterIterator iter, int start, int limit) {2098Font2D font2d = getFont2D();2099char c = iter.setIndex(start);2100for (int i = start; i < limit; i++, c = iter.next()) {2101if (font2d.canDisplay(c)) {2102continue;2103}2104if (!Character.isHighSurrogate(c)) {2105return i;2106}2107char c2 = iter.next();2108// c2 could be CharacterIterator.DONE which is not a low surrogate.2109if (!Character.isLowSurrogate(c2)) {2110return i;2111}2112if (!font2d.canDisplay(Character.toCodePoint(c, c2))) {2113return i;2114}2115i++;2116}2117return -1;2118}21192120/**2121* Returns the italic angle of this <code>Font</code>. The italic angle2122* is the inverse slope of the caret which best matches the posture of this2123* <code>Font</code>.2124* @see TextAttribute#POSTURE2125* @return the angle of the ITALIC style of this <code>Font</code>.2126*/2127public float getItalicAngle() {2128return getItalicAngle(null);2129}21302131/* The FRC hints don't affect the value of the italic angle but2132* we need to pass them in to look up a strike.2133* If we can pass in ones already being used it can prevent an extra2134* strike from being allocated. Note that since italic angle is2135* a property of the font, the font transform is needed not the2136* device transform. Finally, this is private but the only caller of this2137* in the JDK - and the only likely caller - is in this same class.2138*/2139private float getItalicAngle(FontRenderContext frc) {2140Object aa, fm;2141if (frc == null) {2142aa = RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;2143fm = RenderingHints.VALUE_FRACTIONALMETRICS_OFF;2144} else {2145aa = frc.getAntiAliasingHint();2146fm = frc.getFractionalMetricsHint();2147}2148return getFont2D().getItalicAngle(this, identityTx, aa, fm);2149}21502151/**2152* Checks whether or not this <code>Font</code> has uniform2153* line metrics. A logical <code>Font</code> might be a2154* composite font, which means that it is composed of different2155* physical fonts to cover different code ranges. Each of these2156* fonts might have different <code>LineMetrics</code>. If the2157* logical <code>Font</code> is a single2158* font then the metrics would be uniform.2159* @return <code>true</code> if this <code>Font</code> has2160* uniform line metrics; <code>false</code> otherwise.2161*/2162public boolean hasUniformLineMetrics() {2163return false; // REMIND always safe, but prevents caller optimize2164}21652166private transient SoftReference<FontLineMetrics> flmref;2167private FontLineMetrics defaultLineMetrics(FontRenderContext frc) {2168FontLineMetrics flm = null;2169if (flmref == null2170|| (flm = flmref.get()) == null2171|| !flm.frc.equals(frc)) {21722173/* The device transform in the frc is not used in obtaining line2174* metrics, although it probably should be: REMIND find why not?2175* The font transform is used but its applied in getFontMetrics, so2176* just pass identity here2177*/2178float [] metrics = new float[8];2179getFont2D().getFontMetrics(this, identityTx,2180frc.getAntiAliasingHint(),2181frc.getFractionalMetricsHint(),2182metrics);2183float ascent = metrics[0];2184float descent = metrics[1];2185float leading = metrics[2];2186float ssOffset = 0;2187if (values != null && values.getSuperscript() != 0) {2188ssOffset = (float)getTransform().getTranslateY();2189ascent -= ssOffset;2190descent += ssOffset;2191}2192float height = ascent + descent + leading;21932194int baselineIndex = 0; // need real index, assumes roman for everything2195// need real baselines eventually2196float[] baselineOffsets = { 0, (descent/2f - ascent) / 2f, -ascent };21972198float strikethroughOffset = metrics[4];2199float strikethroughThickness = metrics[5];22002201float underlineOffset = metrics[6];2202float underlineThickness = metrics[7];22032204float italicAngle = getItalicAngle(frc);22052206if (isTransformed()) {2207AffineTransform ctx = values.getCharTransform(); // extract rotation2208if (ctx != null) {2209Point2D.Float pt = new Point2D.Float();2210pt.setLocation(0, strikethroughOffset);2211ctx.deltaTransform(pt, pt);2212strikethroughOffset = pt.y;2213pt.setLocation(0, strikethroughThickness);2214ctx.deltaTransform(pt, pt);2215strikethroughThickness = pt.y;2216pt.setLocation(0, underlineOffset);2217ctx.deltaTransform(pt, pt);2218underlineOffset = pt.y;2219pt.setLocation(0, underlineThickness);2220ctx.deltaTransform(pt, pt);2221underlineThickness = pt.y;2222}2223}2224strikethroughOffset += ssOffset;2225underlineOffset += ssOffset;22262227CoreMetrics cm = new CoreMetrics(ascent, descent, leading, height,2228baselineIndex, baselineOffsets,2229strikethroughOffset, strikethroughThickness,2230underlineOffset, underlineThickness,2231ssOffset, italicAngle);22322233flm = new FontLineMetrics(0, cm, frc);2234flmref = new SoftReference<FontLineMetrics>(flm);2235}22362237return (FontLineMetrics)flm.clone();2238}22392240/**2241* Returns a {@link LineMetrics} object created with the specified2242* <code>String</code> and {@link FontRenderContext}.2243* @param str the specified <code>String</code>2244* @param frc the specified <code>FontRenderContext</code>2245* @return a <code>LineMetrics</code> object created with the2246* specified <code>String</code> and {@link FontRenderContext}.2247*/2248public LineMetrics getLineMetrics( String str, FontRenderContext frc) {2249FontLineMetrics flm = defaultLineMetrics(frc);2250flm.numchars = str.length();2251return flm;2252}22532254/**2255* Returns a <code>LineMetrics</code> object created with the2256* specified arguments.2257* @param str the specified <code>String</code>2258* @param beginIndex the initial offset of <code>str</code>2259* @param limit the end offset of <code>str</code>2260* @param frc the specified <code>FontRenderContext</code>2261* @return a <code>LineMetrics</code> object created with the2262* specified arguments.2263*/2264public LineMetrics getLineMetrics( String str,2265int beginIndex, int limit,2266FontRenderContext frc) {2267FontLineMetrics flm = defaultLineMetrics(frc);2268int numChars = limit - beginIndex;2269flm.numchars = (numChars < 0)? 0: numChars;2270return flm;2271}22722273/**2274* Returns a <code>LineMetrics</code> object created with the2275* specified arguments.2276* @param chars an array of characters2277* @param beginIndex the initial offset of <code>chars</code>2278* @param limit the end offset of <code>chars</code>2279* @param frc the specified <code>FontRenderContext</code>2280* @return a <code>LineMetrics</code> object created with the2281* specified arguments.2282*/2283public LineMetrics getLineMetrics(char [] chars,2284int beginIndex, int limit,2285FontRenderContext frc) {2286FontLineMetrics flm = defaultLineMetrics(frc);2287int numChars = limit - beginIndex;2288flm.numchars = (numChars < 0)? 0: numChars;2289return flm;2290}22912292/**2293* Returns a <code>LineMetrics</code> object created with the2294* specified arguments.2295* @param ci the specified <code>CharacterIterator</code>2296* @param beginIndex the initial offset in <code>ci</code>2297* @param limit the end offset of <code>ci</code>2298* @param frc the specified <code>FontRenderContext</code>2299* @return a <code>LineMetrics</code> object created with the2300* specified arguments.2301*/2302public LineMetrics getLineMetrics(CharacterIterator ci,2303int beginIndex, int limit,2304FontRenderContext frc) {2305FontLineMetrics flm = defaultLineMetrics(frc);2306int numChars = limit - beginIndex;2307flm.numchars = (numChars < 0)? 0: numChars;2308return flm;2309}23102311/**2312* Returns the logical bounds of the specified <code>String</code> in2313* the specified <code>FontRenderContext</code>. The logical bounds2314* contains the origin, ascent, advance, and height, which includes2315* the leading. The logical bounds does not always enclose all the2316* text. For example, in some languages and in some fonts, accent2317* marks can be positioned above the ascent or below the descent.2318* To obtain a visual bounding box, which encloses all the text,2319* use the {@link TextLayout#getBounds() getBounds} method of2320* <code>TextLayout</code>.2321* <p>Note: The returned bounds is in baseline-relative coordinates2322* (see {@link java.awt.Font class notes}).2323* @param str the specified <code>String</code>2324* @param frc the specified <code>FontRenderContext</code>2325* @return a {@link Rectangle2D} that is the bounding box of the2326* specified <code>String</code> in the specified2327* <code>FontRenderContext</code>.2328* @see FontRenderContext2329* @see Font#createGlyphVector2330* @since 1.22331*/2332public Rectangle2D getStringBounds( String str, FontRenderContext frc) {2333char[] array = str.toCharArray();2334return getStringBounds(array, 0, array.length, frc);2335}23362337/**2338* Returns the logical bounds of the specified <code>String</code> in2339* the specified <code>FontRenderContext</code>. The logical bounds2340* contains the origin, ascent, advance, and height, which includes2341* the leading. The logical bounds does not always enclose all the2342* text. For example, in some languages and in some fonts, accent2343* marks can be positioned above the ascent or below the descent.2344* To obtain a visual bounding box, which encloses all the text,2345* use the {@link TextLayout#getBounds() getBounds} method of2346* <code>TextLayout</code>.2347* <p>Note: The returned bounds is in baseline-relative coordinates2348* (see {@link java.awt.Font class notes}).2349* @param str the specified <code>String</code>2350* @param beginIndex the initial offset of <code>str</code>2351* @param limit the end offset of <code>str</code>2352* @param frc the specified <code>FontRenderContext</code>2353* @return a <code>Rectangle2D</code> that is the bounding box of the2354* specified <code>String</code> in the specified2355* <code>FontRenderContext</code>.2356* @throws IndexOutOfBoundsException if <code>beginIndex</code> is2357* less than zero, or <code>limit</code> is greater than the2358* length of <code>str</code>, or <code>beginIndex</code>2359* is greater than <code>limit</code>.2360* @see FontRenderContext2361* @see Font#createGlyphVector2362* @since 1.22363*/2364public Rectangle2D getStringBounds( String str,2365int beginIndex, int limit,2366FontRenderContext frc) {2367String substr = str.substring(beginIndex, limit);2368return getStringBounds(substr, frc);2369}23702371/**2372* Returns the logical bounds of the specified array of characters2373* in the specified <code>FontRenderContext</code>. The logical2374* bounds contains the origin, ascent, advance, and height, which2375* includes the leading. The logical bounds does not always enclose2376* all the text. For example, in some languages and in some fonts,2377* accent marks can be positioned above the ascent or below the2378* descent. To obtain a visual bounding box, which encloses all the2379* text, use the {@link TextLayout#getBounds() getBounds} method of2380* <code>TextLayout</code>.2381* <p>Note: The returned bounds is in baseline-relative coordinates2382* (see {@link java.awt.Font class notes}).2383* @param chars an array of characters2384* @param beginIndex the initial offset in the array of2385* characters2386* @param limit the end offset in the array of characters2387* @param frc the specified <code>FontRenderContext</code>2388* @return a <code>Rectangle2D</code> that is the bounding box of the2389* specified array of characters in the specified2390* <code>FontRenderContext</code>.2391* @throws IndexOutOfBoundsException if <code>beginIndex</code> is2392* less than zero, or <code>limit</code> is greater than the2393* length of <code>chars</code>, or <code>beginIndex</code>2394* is greater than <code>limit</code>.2395* @see FontRenderContext2396* @see Font#createGlyphVector2397* @since 1.22398*/2399public Rectangle2D getStringBounds(char [] chars,2400int beginIndex, int limit,2401FontRenderContext frc) {2402if (beginIndex < 0) {2403throw new IndexOutOfBoundsException("beginIndex: " + beginIndex);2404}2405if (limit > chars.length) {2406throw new IndexOutOfBoundsException("limit: " + limit);2407}2408if (beginIndex > limit) {2409throw new IndexOutOfBoundsException("range length: " +2410(limit - beginIndex));2411}24122413// this code should be in textlayout2414// quick check for simple text, assume GV ok to use if simple24152416boolean simple = values == null ||2417(values.getKerning() == 0 && values.getLigatures() == 0 &&2418values.getBaselineTransform() == null);2419if (simple) {2420simple = ! FontUtilities.isComplexText(chars, beginIndex, limit);2421}24222423if (simple) {2424GlyphVector gv = new StandardGlyphVector(this, chars, beginIndex,2425limit - beginIndex, frc);2426return gv.getLogicalBounds();2427} else {2428// need char array constructor on textlayout2429String str = new String(chars, beginIndex, limit - beginIndex);2430TextLayout tl = new TextLayout(str, this, frc);2431return new Rectangle2D.Float(0, -tl.getAscent(), tl.getAdvance(),2432tl.getAscent() + tl.getDescent() +2433tl.getLeading());2434}2435}24362437/**2438* Returns the logical bounds of the characters indexed in the2439* specified {@link CharacterIterator} in the2440* specified <code>FontRenderContext</code>. The logical bounds2441* contains the origin, ascent, advance, and height, which includes2442* the leading. The logical bounds does not always enclose all the2443* text. For example, in some languages and in some fonts, accent2444* marks can be positioned above the ascent or below the descent.2445* To obtain a visual bounding box, which encloses all the text,2446* use the {@link TextLayout#getBounds() getBounds} method of2447* <code>TextLayout</code>.2448* <p>Note: The returned bounds is in baseline-relative coordinates2449* (see {@link java.awt.Font class notes}).2450* @param ci the specified <code>CharacterIterator</code>2451* @param beginIndex the initial offset in <code>ci</code>2452* @param limit the end offset in <code>ci</code>2453* @param frc the specified <code>FontRenderContext</code>2454* @return a <code>Rectangle2D</code> that is the bounding box of the2455* characters indexed in the specified <code>CharacterIterator</code>2456* in the specified <code>FontRenderContext</code>.2457* @see FontRenderContext2458* @see Font#createGlyphVector2459* @since 1.22460* @throws IndexOutOfBoundsException if <code>beginIndex</code> is2461* less than the start index of <code>ci</code>, or2462* <code>limit</code> is greater than the end index of2463* <code>ci</code>, or <code>beginIndex</code> is greater2464* than <code>limit</code>2465*/2466public Rectangle2D getStringBounds(CharacterIterator ci,2467int beginIndex, int limit,2468FontRenderContext frc) {2469int start = ci.getBeginIndex();2470int end = ci.getEndIndex();24712472if (beginIndex < start) {2473throw new IndexOutOfBoundsException("beginIndex: " + beginIndex);2474}2475if (limit > end) {2476throw new IndexOutOfBoundsException("limit: " + limit);2477}2478if (beginIndex > limit) {2479throw new IndexOutOfBoundsException("range length: " +2480(limit - beginIndex));2481}24822483char[] arr = new char[limit - beginIndex];24842485ci.setIndex(beginIndex);2486for(int idx = 0; idx < arr.length; idx++) {2487arr[idx] = ci.current();2488ci.next();2489}24902491return getStringBounds(arr,0,arr.length,frc);2492}24932494/**2495* Returns the bounds for the character with the maximum2496* bounds as defined in the specified <code>FontRenderContext</code>.2497* <p>Note: The returned bounds is in baseline-relative coordinates2498* (see {@link java.awt.Font class notes}).2499* @param frc the specified <code>FontRenderContext</code>2500* @return a <code>Rectangle2D</code> that is the bounding box2501* for the character with the maximum bounds.2502*/2503public Rectangle2D getMaxCharBounds(FontRenderContext frc) {2504float [] metrics = new float[4];25052506getFont2D().getFontMetrics(this, frc, metrics);25072508return new Rectangle2D.Float(0, -metrics[0],2509metrics[3],2510metrics[0] + metrics[1] + metrics[2]);2511}25122513/**2514* Creates a {@link java.awt.font.GlyphVector GlyphVector} by2515* mapping characters to glyphs one-to-one based on the2516* Unicode cmap in this <code>Font</code>. This method does no other2517* processing besides the mapping of glyphs to characters. This2518* means that this method is not useful for some scripts, such2519* as Arabic, Hebrew, Thai, and Indic, that require reordering,2520* shaping, or ligature substitution.2521* @param frc the specified <code>FontRenderContext</code>2522* @param str the specified <code>String</code>2523* @return a new <code>GlyphVector</code> created with the2524* specified <code>String</code> and the specified2525* <code>FontRenderContext</code>.2526*/2527public GlyphVector createGlyphVector(FontRenderContext frc, String str)2528{2529return (GlyphVector)new StandardGlyphVector(this, str, frc);2530}25312532/**2533* Creates a {@link java.awt.font.GlyphVector GlyphVector} by2534* mapping characters to glyphs one-to-one based on the2535* Unicode cmap in this <code>Font</code>. This method does no other2536* processing besides the mapping of glyphs to characters. This2537* means that this method is not useful for some scripts, such2538* as Arabic, Hebrew, Thai, and Indic, that require reordering,2539* shaping, or ligature substitution.2540* @param frc the specified <code>FontRenderContext</code>2541* @param chars the specified array of characters2542* @return a new <code>GlyphVector</code> created with the2543* specified array of characters and the specified2544* <code>FontRenderContext</code>.2545*/2546public GlyphVector createGlyphVector(FontRenderContext frc, char[] chars)2547{2548return (GlyphVector)new StandardGlyphVector(this, chars, frc);2549}25502551/**2552* Creates a {@link java.awt.font.GlyphVector GlyphVector} by2553* mapping the specified characters to glyphs one-to-one based on the2554* Unicode cmap in this <code>Font</code>. This method does no other2555* processing besides the mapping of glyphs to characters. This2556* means that this method is not useful for some scripts, such2557* as Arabic, Hebrew, Thai, and Indic, that require reordering,2558* shaping, or ligature substitution.2559* @param frc the specified <code>FontRenderContext</code>2560* @param ci the specified <code>CharacterIterator</code>2561* @return a new <code>GlyphVector</code> created with the2562* specified <code>CharacterIterator</code> and the specified2563* <code>FontRenderContext</code>.2564*/2565public GlyphVector createGlyphVector( FontRenderContext frc,2566CharacterIterator ci)2567{2568return (GlyphVector)new StandardGlyphVector(this, ci, frc);2569}25702571/**2572* Creates a {@link java.awt.font.GlyphVector GlyphVector} by2573* mapping characters to glyphs one-to-one based on the2574* Unicode cmap in this <code>Font</code>. This method does no other2575* processing besides the mapping of glyphs to characters. This2576* means that this method is not useful for some scripts, such2577* as Arabic, Hebrew, Thai, and Indic, that require reordering,2578* shaping, or ligature substitution.2579* @param frc the specified <code>FontRenderContext</code>2580* @param glyphCodes the specified integer array2581* @return a new <code>GlyphVector</code> created with the2582* specified integer array and the specified2583* <code>FontRenderContext</code>.2584*/2585public GlyphVector createGlyphVector( FontRenderContext frc,2586int [] glyphCodes)2587{2588return (GlyphVector)new StandardGlyphVector(this, glyphCodes, frc);2589}25902591/**2592* Returns a new <code>GlyphVector</code> object, performing full2593* layout of the text if possible. Full layout is required for2594* complex text, such as Arabic or Hindi. Support for different2595* scripts depends on the font and implementation.2596* <p>2597* Layout requires bidi analysis, as performed by2598* <code>Bidi</code>, and should only be performed on text that2599* has a uniform direction. The direction is indicated in the2600* flags parameter,by using LAYOUT_RIGHT_TO_LEFT to indicate a2601* right-to-left (Arabic and Hebrew) run direction, or2602* LAYOUT_LEFT_TO_RIGHT to indicate a left-to-right (English)2603* run direction.2604* <p>2605* In addition, some operations, such as Arabic shaping, require2606* context, so that the characters at the start and limit can have2607* the proper shapes. Sometimes the data in the buffer outside2608* the provided range does not have valid data. The values2609* LAYOUT_NO_START_CONTEXT and LAYOUT_NO_LIMIT_CONTEXT can be2610* added to the flags parameter to indicate that the text before2611* start, or after limit, respectively, should not be examined2612* for context.2613* <p>2614* All other values for the flags parameter are reserved.2615*2616* @param frc the specified <code>FontRenderContext</code>2617* @param text the text to layout2618* @param start the start of the text to use for the <code>GlyphVector</code>2619* @param limit the limit of the text to use for the <code>GlyphVector</code>2620* @param flags control flags as described above2621* @return a new <code>GlyphVector</code> representing the text between2622* start and limit, with glyphs chosen and positioned so as to best represent2623* the text2624* @throws ArrayIndexOutOfBoundsException if start or limit is2625* out of bounds2626* @see java.text.Bidi2627* @see #LAYOUT_LEFT_TO_RIGHT2628* @see #LAYOUT_RIGHT_TO_LEFT2629* @see #LAYOUT_NO_START_CONTEXT2630* @see #LAYOUT_NO_LIMIT_CONTEXT2631* @since 1.42632*/2633public GlyphVector layoutGlyphVector(FontRenderContext frc,2634char[] text,2635int start,2636int limit,2637int flags) {26382639GlyphLayout gl = GlyphLayout.get(null); // !!! no custom layout engines2640StandardGlyphVector gv = gl.layout(this, frc, text,2641start, limit-start, flags, null);2642GlyphLayout.done(gl);2643return gv;2644}26452646/**2647* A flag to layoutGlyphVector indicating that text is left-to-right as2648* determined by Bidi analysis.2649*/2650public static final int LAYOUT_LEFT_TO_RIGHT = 0;26512652/**2653* A flag to layoutGlyphVector indicating that text is right-to-left as2654* determined by Bidi analysis.2655*/2656public static final int LAYOUT_RIGHT_TO_LEFT = 1;26572658/**2659* A flag to layoutGlyphVector indicating that text in the char array2660* before the indicated start should not be examined.2661*/2662public static final int LAYOUT_NO_START_CONTEXT = 2;26632664/**2665* A flag to layoutGlyphVector indicating that text in the char array2666* after the indicated limit should not be examined.2667*/2668public static final int LAYOUT_NO_LIMIT_CONTEXT = 4;266926702671private static void applyTransform(AffineTransform trans, AttributeValues values) {2672if (trans == null) {2673throw new IllegalArgumentException("transform must not be null");2674}2675values.setTransform(trans);2676}26772678private static void applyStyle(int style, AttributeValues values) {2679// WEIGHT_BOLD, WEIGHT_REGULAR2680values.setWeight((style & BOLD) != 0 ? 2f : 1f);2681// POSTURE_OBLIQUE, POSTURE_REGULAR2682values.setPosture((style & ITALIC) != 0 ? .2f : 0f);2683}26842685/*2686* Initialize JNI field and method IDs2687*/2688private static native void initIDs();2689}269026912692