2652 lines · 106.0 KB · Java
RawDownload
/* * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.font.FontRenderContext;import java.awt.font.GlyphVector;import java.awt.font.LineMetrics;import java.awt.font.TextAttribute;import java.awt.font.TextLayout;import java.awt.geom.AffineTransform;import java.awt.geom.Point2D;import java.awt.geom.Rectangle2D;import java.awt.peer.FontPeer;import java.io.*;import java.lang.ref.SoftReference;import java.security.AccessController;import java.security.PrivilegedExceptionAction;import java.text.AttributedCharacterIterator.Attribute;import java.text.CharacterIterator;import java.text.StringCharacterIterator;import java.util.Hashtable;import java.util.Locale;import java.util.Map;import sun.font.StandardGlyphVector; import sun.font.AttributeMap;import sun.font.AttributeValues;import sun.font.CompositeFont;import sun.font.CreatedFontTracker;import sun.font.Font2D;import sun.font.Font2DHandle;import sun.font.FontAccess;import sun.font.FontManager;import sun.font.FontManagerFactory;import sun.font.FontUtilities;import sun.font.GlyphLayout;import sun.font.FontLineMetrics;import sun.font.CoreMetrics; import static sun.font.EAttribute.*; /** * The <code>Font</code> class represents fonts, which are used to * render text in a visible way. * A font provides the information needed to map sequences of * <em>characters</em> to sequences of <em>glyphs</em> * and to render sequences of glyphs on <code>Graphics</code> and * <code>Component</code> objects. * * <h4>Characters and Glyphs</h4> * * A <em>character</em> is a symbol that represents an item such as a letter, * a digit, or punctuation in an abstract way. For example, <code>'g'</code>, * <font size=-1>LATIN SMALL LETTER G</font>, is a character. * <p> * A <em>glyph</em> is a shape used to render a character or a sequence of * characters. In simple writing systems, such as Latin, typically one glyph * represents one character. In general, however, characters and glyphs do not * have one-to-one correspondence. For example, the character '&aacute;' * <font size=-1>LATIN SMALL LETTER A WITH ACUTE</font>, can be represented by * two glyphs: one for 'a' and one for '&acute;'. On the other hand, the * two-character string "fi" can be represented by a single glyph, an * "fi" ligature. In complex writing systems, such as Arabic or the South * and South-East Asian writing systems, the relationship between characters * and glyphs can be more complicated and involve context-dependent selection * of glyphs as well as glyph reordering. * * A font encapsulates the collection of glyphs needed to render a selected set * of characters as well as the tables needed to map sequences of characters to * corresponding sequences of glyphs. * * <h4>Physical and Logical Fonts</h4> * * The Java Platform distinguishes between two kinds of fonts: * <em>physical</em> fonts and <em>logical</em> fonts. * <p> * <em>Physical</em> fonts are the actual font libraries containing glyph data * and tables to map from character sequences to glyph sequences, using a font * technology such as TrueType or PostScript Type 1. * All implementations of the Java Platform must support TrueType fonts; * support for other font technologies is implementation dependent. * Physical fonts may use names such as Helvetica, Palatino, HonMincho, or * any number of other font names. * Typically, each physical font supports only a limited set of writing * systems, for example, only Latin characters or only Japanese and Basic * Latin. * The set of available physical fonts varies between configurations. * Applications that require specific fonts can bundle them and instantiate * them using the {@link #createFont createFont} method. * <p> * <em>Logical</em> fonts are the five font families defined by the Java * platform which must be supported by any Java runtime environment: * Serif, SansSerif, Monospaced, Dialog, and DialogInput. * These logical fonts are not actual font libraries. Instead, the logical * font names are mapped to physical fonts by the Java runtime environment. * The mapping is implementation and usually locale dependent, so the look * and the metrics provided by them vary. * Typically, each logical font name maps to several physical fonts in order to * cover a large range of characters. * <p> * Peered AWT components, such as {@link Label Label} and * {@link TextField TextField}, can only use logical fonts. * <p> * For a discussion of the relative advantages and disadvantages of using * physical or logical fonts, see the * <a href="http://java.sun.com/j2se/corejava/intl/reference/faqs/index.html#desktop-rendering">Internationalization FAQ</a> * document. * * <h4>Font Faces and Names</h4> * * A <code>Font</code> * can have many faces, such as heavy, medium, oblique, gothic and * regular. All of these faces have similar typographic design. * <p> * There are three different names that you can get from a * <code>Font</code> object.  The <em>logical font name</em> is simply the * name that was used to construct the font. * The <em>font face name</em>, or just <em>font name</em> for * short, is the name of a particular font face, like Helvetica Bold. The * <em>family name</em> is the name of the font family that determines the * typographic design across several faces, like Helvetica. * <p> * The <code>Font</code> class represents an instance of a font face from * a collection of  font faces that are present in the system resources * of the host system.  As examples, Arial Bold and Courier Bold Italic * are font faces.  There can be several <code>Font</code> objects * associated with a font face, each differing in size, style, transform * and font features. * <p> * The {@link GraphicsEnvironment#getAllFonts() getAllFonts} method * of the <code>GraphicsEnvironment</code> class returns an * array of all font faces available in the system. These font faces are * returned as <code>Font</code> objects with a size of 1, identity * transform and default font features. These * base fonts can then be used to derive new <code>Font</code> objects * with varying sizes, styles, transforms and font features via the * <code>deriveFont</code> methods in this class. * * <h4>Font and TextAttribute</h4> * * <p><code>Font</code> supports most * <code>TextAttribute</code>s.  This makes some operations, such as * rendering underlined text, convenient since it is not * necessary to explicitly construct a <code>TextLayout</code> object. * Attributes can be set on a Font by constructing or deriving it * using a <code>Map</code> of <code>TextAttribute</code> values. * * <p>The values of some <code>TextAttributes</code> are not * serializable, and therefore attempting to serialize an instance of * <code>Font</code> that has such values will not serialize them. * This means a Font deserialized from such a stream will not compare * equal to the original Font that contained the non-serializable * attributes.  This should very rarely pose a problem * since these attributes are typically used only in special * circumstances and are unlikely to be serialized. * * <ul> * <li><code>FOREGROUND</code> and <code>BACKGROUND</code> use * <code>Paint</code> values. The subclass <code>Color</code> is * serializable, while <code>GradientPaint</code> and * <code>TexturePaint</code> are not.</li> * <li><code>CHAR_REPLACEMENT</code> uses * <code>GraphicAttribute</code> values.  The subclasses * <code>ShapeGraphicAttribute</code> and * <code>ImageGraphicAttribute</code> are not serializable.</li> * <li><code>INPUT_METHOD_HIGHLIGHT</code> uses * <code>InputMethodHighlight</code> values, which are * not serializable.  See {@link java.awt.im.InputMethodHighlight}.</li> * </ul> * * Clients who create custom subclasses of <code>Paint</code> and * <code>GraphicAttribute</code> can make them serializable and * avoid this problem.  Clients who use input method highlights can * convert these to the platform-specific attributes for that * highlight on the current platform and set them on the Font as * a workaround.</p> * * <p>The <code>Map</code>-based constructor and * <code>deriveFont</code> APIs ignore the FONT attribute, and it is * not retained by the Font; the static {@link #getFont} method should * be used if the FONT attribute might be present.  See {@link * java.awt.font.TextAttribute#FONT} for more information.</p> * * <p>Several attributes will cause additional rendering overhead * and potentially invoke layout.  If a <code>Font</code> has such * attributes, the <code>{@link #hasLayoutAttributes()}</code> method * will return true.</p> * * <p>Note: Font rotations can cause text baselines to be rotated.  In * order to account for this (rare) possibility, font APIs are * specified to return metrics and take parameters 'in * baseline-relative coordinates'.  This maps the 'x' coordinate to * the advance along the baseline, (positive x is forward along the * baseline), and the 'y' coordinate to a distance along the * perpendicular to the baseline at 'x' (positive y is 90 degrees * clockwise from the baseline vector).  APIs for which this is * especially important are called out as having 'baseline-relative * coordinates.' */public class Font implements java.io.Serializable{    private static class FontAccessImpl extends FontAccess {        public Font2D getFont2D(Font font) {            return font.getFont2D();        }         public void setFont2D(Font font, Font2DHandle handle) {            font.font2DHandle = handle;        }         public void setCreatedFont(Font font) {            font.createdFont = true;        }         public boolean isCreatedFont(Font font) {            return font.createdFont;        }    }     static {        /* ensure that the necessary native libraries are loaded */        Toolkit.loadLibraries();        initIDs();        FontAccess.setFontAccess(new FontAccessImpl());    }     /**     * This is now only used during serialization.  Typically     * it is null.     *     * @serial     * @see #getAttributes()     */    private Hashtable fRequestedAttributes;     /*     * Constants to be used for logical font family names.     */     /**     * A String constant for the canonical family name of the     * logical font "Dialog". It is useful in Font construction     * to provide compile-time verification of the name.     * @since 1.6     */    public static final String DIALOG = "Dialog";     /**     * A String constant for the canonical family name of the     * logical font "DialogInput". It is useful in Font construction     * to provide compile-time verification of the name.     * @since 1.6     */    public static final String DIALOG_INPUT = "DialogInput";     /**     * A String constant for the canonical family name of the     * logical font "SansSerif". It is useful in Font construction     * to provide compile-time verification of the name.     * @since 1.6     */    public static final String SANS_SERIF = "SansSerif";     /**     * A String constant for the canonical family name of the     * logical font "Serif". It is useful in Font construction     * to provide compile-time verification of the name.     * @since 1.6     */    public static final String SERIF = "Serif";     /**     * A String constant for the canonical family name of the     * logical font "Monospaced". It is useful in Font construction     * to provide compile-time verification of the name.     * @since 1.6     */    public static final String MONOSPACED = "Monospaced";     /*     * Constants to be used for styles. Can be combined to mix     * styles.     */     /**     * The plain style constant.     */    public static final int PLAIN       = 0;     /**     * The bold style constant.  This can be combined with the other style     * constants (except PLAIN) for mixed styles.     */    public static final int BOLD        = 1;     /**     * The italicized style constant.  This can be combined with the other     * style constants (except PLAIN) for mixed styles.     */    public static final int ITALIC      = 2;     /**     * The baseline used in most Roman scripts when laying out text.     */    public static final int ROMAN_BASELINE = 0;     /**     * The baseline used in ideographic scripts like Chinese, Japanese,     * and Korean when laying out text.     */    public static final int CENTER_BASELINE = 1;     /**     * The baseline used in Devanigiri and similar scripts when laying     * out text.     */    public static final int HANGING_BASELINE = 2;     /**     * Identify a font resource of type TRUETYPE.     * Used to specify a TrueType font resource to the     * {@link #createFont} method.     * The TrueType format was extended to become the OpenType     * format, which adds support for fonts with Postscript outlines,     * this tag therefore references these fonts, as well as those     * with TrueType outlines.     * @since 1.3     */     public static final int TRUETYPE_FONT = 0;     /**     * Identify a font resource of type TYPE1.     * Used to specify a Type1 font resource to the     * {@link #createFont} method.     * @since 1.5     */    public static final int TYPE1_FONT = 1;     /**     * The logical name of this <code>Font</code>, as passed to the     * constructor.     * @since JDK1.0     *     * @serial     * @see #getName     */    protected String name;     /**     * The style of this <code>Font</code>, as passed to the constructor.     * This style can be PLAIN, BOLD, ITALIC, or BOLD+ITALIC.     * @since JDK1.0     *     * @serial     * @see #getStyle()     */    protected int style;     /**     * The point size of this <code>Font</code>, rounded to integer.     * @since JDK1.0     *     * @serial     * @see #getSize()     */    protected int size;     /**     * The point size of this <code>Font</code> in <code>float</code>.     *     * @serial     * @see #getSize()     * @see #getSize2D()     */    protected float pointSize;     /**     * The platform specific font information.     */    private transient FontPeer peer;    private transient long pData;       // native JDK1.1 font pointer    private transient Font2DHandle font2DHandle;     private transient AttributeValues values;    private transient boolean hasLayoutAttributes;     /*     * If the origin of a Font is a created font then this attribute     * must be set on all derived fonts too.     */    private transient boolean createdFont = false;     /*     * This is true if the font transform is not identity.  It     * is used to avoid unnecessary instantiation of an AffineTransform.     */    private transient boolean nonIdentityTx;     /*     * A cached value used when a transform is required for internal     * use.  This must not be exposed to callers since AffineTransform     * is mutable.     */    private static final AffineTransform identityTx = new AffineTransform();     /*     * JDK 1.1 serialVersionUID     */    private static final long serialVersionUID = -4206021311591459213L;     /**     * Gets the peer of this <code>Font</code>.     * @return  the peer of the <code>Font</code>.     * @since JDK1.1     * @deprecated Font rendering is now platform independent.     */    @Deprecated    public FontPeer getPeer(){        return getPeer_NoClientCode();    }    // NOTE: This method is called by privileged threads.    //       We implement this functionality in a package-private method    //       to insure that it cannot be overridden by client subclasses.    //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!    final FontPeer getPeer_NoClientCode() {        if(peer == null) {            Toolkit tk = Toolkit.getDefaultToolkit();            this.peer = tk.getFontPeer(name, style);        }        return peer;    }     /**     * Return the AttributeValues object associated with this     * font.  Most of the time, the internal object is null.     * If required, it will be created from the 'standard'     * state on the font.  Only non-default values will be     * set in the AttributeValues object.     *     * <p>Since the AttributeValues object is mutable, and it     * is cached in the font, care must be taken to ensure that     * it is not mutated.     */    private AttributeValues getAttributeValues() {        if (values == null) {            AttributeValues valuesTmp = new AttributeValues();            valuesTmp.setFamily(name);            valuesTmp.setSize(pointSize); // expects the float value.             if ((style & BOLD) != 0) {                valuesTmp.setWeight(2); // WEIGHT_BOLD            }             if ((style & ITALIC) != 0) {                valuesTmp.setPosture(.2f); // POSTURE_OBLIQUE            }            valuesTmp.defineAll(PRIMARY_MASK); // for streaming compatibility            values = valuesTmp;        }         return values;    }     private Font2D getFont2D() {        FontManager fm = FontManagerFactory.getInstance();        if (fm.usingPerAppContextComposites() &&            font2DHandle != null &&            font2DHandle.font2D instanceof CompositeFont &&            ((CompositeFont)(font2DHandle.font2D)).isStdComposite()) {            return fm.findFont2D(name, style,                                          FontManager.LOGICAL_FALLBACK);        } else if (font2DHandle == null) {            font2DHandle =                fm.findFont2D(name, style,                              FontManager.LOGICAL_FALLBACK).handle;        }

Lines 1–500 of 2652.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t