Home | History | Annotate | Download | only in core
      1 
      2 /*
      3  * Copyright 2006 The Android Open Source Project
      4  *
      5  * Use of this source code is governed by a BSD-style license that can be
      6  * found in the LICENSE file.
      7  */
      8 
      9 
     10 #ifndef SkTypeface_DEFINED
     11 #define SkTypeface_DEFINED
     12 
     13 #include "../private/SkOncePtr.h"
     14 #include "../private/SkWeakRefCnt.h"
     15 #include "SkFontStyle.h"
     16 #include "SkRect.h"
     17 #include "SkString.h"
     18 
     19 class SkDescriptor;
     20 class SkFontData;
     21 class SkFontDescriptor;
     22 class SkScalerContext;
     23 struct SkScalerContextRec;
     24 class SkStream;
     25 class SkStreamAsset;
     26 class SkAdvancedTypefaceMetrics;
     27 class SkWStream;
     28 
     29 typedef uint32_t SkFontID;
     30 /** Machine endian. */
     31 typedef uint32_t SkFontTableTag;
     32 
     33 /** \class SkTypeface
     34 
     35     The SkTypeface class specifies the typeface and intrinsic style of a font.
     36     This is used in the paint, along with optionally algorithmic settings like
     37     textSize, textSkewX, textScaleX, kFakeBoldText_Mask, to specify
     38     how text appears when drawn (and measured).
     39 
     40     Typeface objects are immutable, and so they can be shared between threads.
     41 */
     42 class SK_API SkTypeface : public SkWeakRefCnt {
     43 public:
     44     /** Style specifies the intrinsic style attributes of a given typeface
     45     */
     46     enum Style {
     47         kNormal = 0,
     48         kBold   = 0x01,
     49         kItalic = 0x02,
     50 
     51         // helpers
     52         kBoldItalic = 0x03
     53     };
     54 
     55     /** Returns the typeface's intrinsic style attributes. */
     56     SkFontStyle fontStyle() const {
     57         return fStyle;
     58     }
     59 
     60     /** Returns the typeface's intrinsic style attributes.
     61      *  @deprecated use fontStyle() instead.
     62      */
     63     Style style() const {
     64         return static_cast<Style>(
     65             (fStyle.weight() >= SkFontStyle::kSemiBold_Weight ? kBold : kNormal) |
     66             (fStyle.slant()  != SkFontStyle::kUpright_Slant ? kItalic : kNormal));
     67     }
     68 
     69     /** Returns true if style() has the kBold bit set. */
     70     bool isBold() const { return fStyle.weight() >= SkFontStyle::kSemiBold_Weight; }
     71 
     72     /** Returns true if style() has the kItalic bit set. */
     73     bool isItalic() const { return fStyle.slant() != SkFontStyle::kUpright_Slant; }
     74 
     75     /** Returns true if the typeface claims to be fixed-pitch.
     76      *  This is a style bit, advance widths may vary even if this returns true.
     77      */
     78     bool isFixedPitch() const { return fIsFixedPitch; }
     79 
     80     /** Return a 32bit value for this typeface, unique for the underlying font
     81         data. Will never return 0.
     82      */
     83     SkFontID uniqueID() const { return fUniqueID; }
     84 
     85     /** Return the uniqueID for the specified typeface. If the face is null,
     86         resolve it to the default font and return its uniqueID. Will never
     87         return 0.
     88     */
     89     static SkFontID UniqueID(const SkTypeface* face);
     90 
     91     /** Returns true if the two typefaces reference the same underlying font,
     92         handling either being null (treating null as the default font)
     93      */
     94     static bool Equal(const SkTypeface* facea, const SkTypeface* faceb);
     95 
     96     /**
     97      *  Returns a ref() to the default typeface. The caller must call unref()
     98      *  when they are done referencing the object. Never returns NULL.
     99      */
    100     static SkTypeface* RefDefault(Style style = SkTypeface::kNormal);
    101 
    102     /** Return a new reference to the typeface that most closely matches the
    103         requested familyName and style. Pass null as the familyName to return
    104         the default font for the requested style. Will never return null
    105 
    106         @param familyName  May be NULL. The name of the font family.
    107         @param style       The style (normal, bold, italic) of the typeface.
    108         @return reference to the closest-matching typeface. Call must call
    109                 unref() when they are done.
    110     */
    111     static SkTypeface* CreateFromName(const char familyName[], Style style);
    112 
    113     /** Return a new reference to the typeface that most closely matches the
    114         requested typeface and specified Style. Use this call if you want to
    115         pick a new style from the same family of the existing typeface.
    116         If family is NULL, this selects from the default font's family.
    117 
    118         @param family  May be NULL. The name of the existing type face.
    119         @param s       The style (normal, bold, italic) of the type face.
    120         @return reference to the closest-matching typeface. Call must call
    121                 unref() when they are done.
    122     */
    123     static SkTypeface* CreateFromTypeface(const SkTypeface* family, Style s);
    124 
    125     /** Return a new typeface given a file. If the file does not exist, or is
    126         not a valid font file, returns null.
    127     */
    128     static SkTypeface* CreateFromFile(const char path[], int index = 0);
    129 
    130     /** Return a new typeface given a stream. If the stream is
    131         not a valid font file, returns null. Ownership of the stream is
    132         transferred, so the caller must not reference it again.
    133     */
    134     static SkTypeface* CreateFromStream(SkStreamAsset* stream, int index = 0);
    135 
    136     /** Return a new typeface given font data and configuration. If the data
    137         is not valid font data, returns null. Ownership of the font data is
    138         transferred, so the caller must not reference it again.
    139     */
    140     static SkTypeface* CreateFromFontData(SkFontData*);
    141 
    142     /** Write a unique signature to a stream, sufficient to reconstruct a
    143         typeface referencing the same font when Deserialize is called.
    144      */
    145     void serialize(SkWStream*) const;
    146 
    147     /** Given the data previously written by serialize(), return a new instance
    148         to a typeface referring to the same font. If that font is not available,
    149         return null. If an instance is returned, the caller is responsible for
    150         calling unref() when they are done with it.
    151         Does not affect ownership of SkStream.
    152      */
    153     static SkTypeface* Deserialize(SkStream*);
    154 
    155     enum Encoding {
    156         kUTF8_Encoding,
    157         kUTF16_Encoding,
    158         kUTF32_Encoding
    159     };
    160 
    161     /**
    162      *  Given an array of character codes, of the specified encoding,
    163      *  optionally return their corresponding glyph IDs (if glyphs is not NULL).
    164      *
    165      *  @param chars pointer to the array of character codes
    166      *  @param encoding how the characters are encoded
    167      *  @param glyphs (optional) returns the corresponding glyph IDs for each
    168      *          character code, up to glyphCount values. If a character code is
    169      *          not found in the typeface, the corresponding glyph ID will be 0.
    170      *  @param glyphCount number of code points in 'chars' to process. If glyphs
    171      *          is not NULL, then it must point sufficient memory to write
    172      *          glyphCount values into it.
    173      *  @return the number of number of continuous non-zero glyph IDs computed
    174      *          from the beginning of chars. This value is valid, even if the
    175      *          glyphs parameter is NULL.
    176      */
    177     int charsToGlyphs(const void* chars, Encoding encoding, uint16_t glyphs[],
    178                       int glyphCount) const;
    179 
    180     /**
    181      *  Return the number of glyphs in the typeface.
    182      */
    183     int countGlyphs() const;
    184 
    185     // Table getters -- may fail if the underlying font format is not organized
    186     // as 4-byte tables.
    187 
    188     /** Return the number of tables in the font. */
    189     int countTables() const;
    190 
    191     /** Copy into tags[] (allocated by the caller) the list of table tags in
    192      *  the font, and return the number. This will be the same as CountTables()
    193      *  or 0 if an error occured. If tags == NULL, this only returns the count
    194      *  (the same as calling countTables()).
    195      */
    196     int getTableTags(SkFontTableTag tags[]) const;
    197 
    198     /** Given a table tag, return the size of its contents, or 0 if not present
    199      */
    200     size_t getTableSize(SkFontTableTag) const;
    201 
    202     /** Copy the contents of a table into data (allocated by the caller). Note
    203      *  that the contents of the table will be in their native endian order
    204      *  (which for most truetype tables is big endian). If the table tag is
    205      *  not found, or there is an error copying the data, then 0 is returned.
    206      *  If this happens, it is possible that some or all of the memory pointed
    207      *  to by data may have been written to, even though an error has occured.
    208      *
    209      *  @param fontID the font to copy the table from
    210      *  @param tag  The table tag whose contents are to be copied
    211      *  @param offset The offset in bytes into the table's contents where the
    212      *  copy should start from.
    213      *  @param length The number of bytes, starting at offset, of table data
    214      *  to copy.
    215      *  @param data storage address where the table contents are copied to
    216      *  @return the number of bytes actually copied into data. If offset+length
    217      *  exceeds the table's size, then only the bytes up to the table's
    218      *  size are actually copied, and this is the value returned. If
    219      *  offset > the table's size, or tag is not a valid table,
    220      *  then 0 is returned.
    221      */
    222     size_t getTableData(SkFontTableTag tag, size_t offset, size_t length,
    223                         void* data) const;
    224 
    225     /**
    226      *  Return the units-per-em value for this typeface, or zero if there is an
    227      *  error.
    228      */
    229     int getUnitsPerEm() const;
    230 
    231     /**
    232      *  Given a run of glyphs, return the associated horizontal adjustments.
    233      *  Adjustments are in "design units", which are integers relative to the
    234      *  typeface's units per em (see getUnitsPerEm).
    235      *
    236      *  Some typefaces are known to never support kerning. Calling this method
    237      *  with all zeros (e.g. getKerningPairAdustments(NULL, 0, NULL)) returns
    238      *  a boolean indicating if the typeface might support kerning. If it
    239      *  returns false, then it will always return false (no kerning) for all
    240      *  possible glyph runs. If it returns true, then it *may* return true for
    241      *  somne glyph runs.
    242      *
    243      *  If count is non-zero, then the glyphs parameter must point to at least
    244      *  [count] valid glyph IDs, and the adjustments parameter must be
    245      *  sized to at least [count - 1] entries. If the method returns true, then
    246      *  [count-1] entries in the adjustments array will be set. If the method
    247      *  returns false, then no kerning should be applied, and the adjustments
    248      *  array will be in an undefined state (possibly some values may have been
    249      *  written, but none of them should be interpreted as valid values).
    250      */
    251     bool getKerningPairAdjustments(const uint16_t glyphs[], int count,
    252                                    int32_t adjustments[]) const;
    253 
    254     struct LocalizedString {
    255         SkString fString;
    256         SkString fLanguage;
    257     };
    258     class LocalizedStrings : ::SkNoncopyable {
    259     public:
    260         virtual ~LocalizedStrings() { }
    261         virtual bool next(LocalizedString* localizedString) = 0;
    262         void unref() { delete this; }
    263     };
    264     /**
    265      *  Returns an iterator which will attempt to enumerate all of the
    266      *  family names specified by the font.
    267      *  It is the caller's responsibility to unref() the returned pointer.
    268      */
    269     LocalizedStrings* createFamilyNameIterator() const;
    270 
    271     /**
    272      *  Return the family name for this typeface. It will always be returned
    273      *  encoded as UTF8, but the language of the name is whatever the host
    274      *  platform chooses.
    275      */
    276     void getFamilyName(SkString* name) const;
    277 
    278     /**
    279      *  Return a stream for the contents of the font data, or NULL on failure.
    280      *  If ttcIndex is not null, it is set to the TrueTypeCollection index
    281      *  of this typeface within the stream, or 0 if the stream is not a
    282      *  collection.
    283      *  The caller is responsible for deleting the stream.
    284      */
    285     SkStreamAsset* openStream(int* ttcIndex) const;
    286 
    287     /**
    288      *  Return the font data, or NULL on failure.
    289      *  The caller is responsible for deleting the font data.
    290      */
    291     SkFontData* createFontData() const;
    292 
    293     /**
    294      *  Return a scalercontext for the given descriptor. If this fails, then
    295      *  if allowFailure is true, this returns NULL, else it returns a
    296      *  dummy scalercontext that will not crash, but will draw nothing.
    297      */
    298     SkScalerContext* createScalerContext(const SkDescriptor*,
    299                                          bool allowFailure = false) const;
    300 
    301     /**
    302      *  Return a rectangle (scaled to 1-pt) that represents the union of the bounds of all
    303      *  of the glyphs, but each one positioned at (0,). This may be conservatively large, and
    304      *  will not take into account any hinting or other size-specific adjustments.
    305      */
    306     SkRect getBounds() const;
    307 
    308     // PRIVATE / EXPERIMENTAL -- do not call
    309     void filterRec(SkScalerContextRec* rec) const {
    310         this->onFilterRec(rec);
    311     }
    312     // PRIVATE / EXPERIMENTAL -- do not call
    313     void getFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const {
    314         this->onGetFontDescriptor(desc, isLocal);
    315     }
    316 
    317 protected:
    318     // The type of advance data wanted.
    319     enum PerGlyphInfo {
    320         kNo_PerGlyphInfo         = 0x0, // Don't populate any per glyph info.
    321         kHAdvance_PerGlyphInfo   = 0x1, // Populate horizontal advance data.
    322         kVAdvance_PerGlyphInfo   = 0x2, // Populate vertical advance data.
    323         kGlyphNames_PerGlyphInfo = 0x4, // Populate glyph names (Type 1 only).
    324         kToUnicode_PerGlyphInfo  = 0x8  // Populate ToUnicode table, ignored
    325         // for Type 1 fonts
    326     };
    327 
    328     /** uniqueID must be unique and non-zero
    329     */
    330     SkTypeface(const SkFontStyle& style, SkFontID uniqueID, bool isFixedPitch = false);
    331     virtual ~SkTypeface();
    332 
    333     /** Sets the fixedPitch bit. If used, must be called in the constructor. */
    334     void setIsFixedPitch(bool isFixedPitch) { fIsFixedPitch = isFixedPitch; }
    335 
    336     friend class SkScalerContext;
    337     static SkTypeface* GetDefaultTypeface(Style style = SkTypeface::kNormal);
    338 
    339     virtual SkScalerContext* onCreateScalerContext(const SkDescriptor*) const = 0;
    340     virtual void onFilterRec(SkScalerContextRec*) const = 0;
    341     virtual SkAdvancedTypefaceMetrics* onGetAdvancedTypefaceMetrics(
    342                         PerGlyphInfo,
    343                         const uint32_t* glyphIDs,
    344                         uint32_t glyphIDsCount) const = 0;
    345 
    346     virtual SkStreamAsset* onOpenStream(int* ttcIndex) const = 0;
    347     // TODO: make pure virtual.
    348     virtual SkFontData* onCreateFontData() const;
    349 
    350     virtual void onGetFontDescriptor(SkFontDescriptor*, bool* isLocal) const = 0;
    351 
    352     virtual int onCharsToGlyphs(const void* chars, Encoding, uint16_t glyphs[],
    353                                 int glyphCount) const = 0;
    354     virtual int onCountGlyphs() const = 0;
    355 
    356     virtual int onGetUPEM() const = 0;
    357     virtual bool onGetKerningPairAdjustments(const uint16_t glyphs[], int count,
    358                                              int32_t adjustments[]) const;
    359 
    360     /** Returns the family name of the typeface as known by its font manager.
    361      *  This name may or may not be produced by the family name iterator.
    362      */
    363     virtual void onGetFamilyName(SkString* familyName) const = 0;
    364 
    365     /** Returns an iterator over the family names in the font. */
    366     virtual LocalizedStrings* onCreateFamilyNameIterator() const = 0;
    367 
    368     virtual int onGetTableTags(SkFontTableTag tags[]) const = 0;
    369     virtual size_t onGetTableData(SkFontTableTag, size_t offset,
    370                                   size_t length, void* data) const = 0;
    371 
    372     virtual bool onComputeBounds(SkRect*) const;
    373 
    374 private:
    375     friend class SkGTypeface;
    376     friend class SkRandomTypeface;
    377     friend class SkPDFFont;
    378     friend class SkPDFCIDFont;
    379     friend class GrPathRendering;
    380     friend class GrGLPathRendering;
    381 
    382     /** Retrieve detailed typeface metrics.  Used by the PDF backend.
    383      @param perGlyphInfo Indicate what glyph specific information (advances,
    384      names, etc.) should be populated.
    385      @param glyphIDs  For per-glyph info, specify subset of the font by
    386      giving glyph ids.  Each integer represents a glyph
    387      id.  Passing NULL means all glyphs in the font.
    388      @param glyphIDsCount Number of elements in subsetGlyphIds. Ignored if
    389      glyphIDs is NULL.
    390      @return The returned object has already been referenced.
    391      */
    392     SkAdvancedTypefaceMetrics* getAdvancedTypefaceMetrics(
    393                           PerGlyphInfo,
    394                           const uint32_t* glyphIDs = NULL,
    395                           uint32_t glyphIDsCount = 0) const;
    396 
    397 private:
    398     static SkTypeface* CreateDefault(int style);  // SkLazyPtr requires an int, not a Style.
    399     static void        DeleteDefault(SkTypeface*);
    400 
    401     SkOncePtr<SkRect>   fLazyBounds;
    402     SkFontID            fUniqueID;
    403     SkFontStyle         fStyle;
    404     bool                fIsFixedPitch;
    405 
    406     friend class SkPaint;
    407     friend class SkGlyphCache;  // GetDefaultTypeface
    408 
    409     typedef SkWeakRefCnt INHERITED;
    410 };
    411 
    412 #endif
    413