1 /*
2  * Copyright 2006 The Android Open Source Project
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef SkTypeface_DEFINED
9 #define SkTypeface_DEFINED
10 
11 #include "../private/SkNoncopyable.h"
12 #include "../private/SkOnce.h"
13 #include "../private/SkWeakRefCnt.h"
14 #include "SkFontArguments.h"
15 #include "SkFontParameters.h"
16 #include "SkFontStyle.h"
17 #include "SkRect.h"
18 #include "SkString.h"
19 
20 class SkData;
21 class SkDescriptor;
22 class SkFontData;
23 class SkFontDescriptor;
24 class SkScalerContext;
25 class SkStream;
26 class SkStreamAsset;
27 class SkWStream;
28 struct SkAdvancedTypefaceMetrics;
29 struct SkScalerContextEffects;
30 struct SkScalerContextRec;
31 
32 typedef uint32_t SkFontID;
33 /** Machine endian. */
34 typedef uint32_t SkFontTableTag;
35 
36 /** \class SkTypeface
37 
38     The SkTypeface class specifies the typeface and intrinsic style of a font.
39     This is used in the paint, along with optionally algorithmic settings like
40     textSize, textSkewX, textScaleX, kFakeBoldText_Mask, to specify
41     how text appears when drawn (and measured).
42 
43     Typeface objects are immutable, and so they can be shared between threads.
44 */
45 class SK_API SkTypeface : public SkWeakRefCnt {
46 public:
47     /** Returns the typeface's intrinsic style attributes. */
fontStyle()48     SkFontStyle fontStyle() const {
49         return fStyle;
50     }
51 
52     /** Returns true if style() has the kBold bit set. */
isBold()53     bool isBold() const { return fStyle.weight() >= SkFontStyle::kSemiBold_Weight; }
54 
55     /** Returns true if style() has the kItalic bit set. */
isItalic()56     bool isItalic() const { return fStyle.slant() != SkFontStyle::kUpright_Slant; }
57 
58     /** Returns true if the typeface claims to be fixed-pitch.
59      *  This is a style bit, advance widths may vary even if this returns true.
60      */
isFixedPitch()61     bool isFixedPitch() const { return fIsFixedPitch; }
62 
63     /** Copy into 'coordinates' (allocated by the caller) the design variation coordinates.
64      *
65      *  @param coordinates the buffer into which to write the design variation coordinates.
66      *  @param coordinateCount the number of entries available through 'coordinates'.
67      *
68      *  @return The number of axes, or -1 if there is an error.
69      *  If 'coordinates != nullptr' and 'coordinateCount >= numAxes' then 'coordinates' will be
70      *  filled with the variation coordinates describing the position of this typeface in design
71      *  variation space. It is possible the number of axes can be retrieved but actual position
72      *  cannot.
73      */
74     int getVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],
75                                    int coordinateCount) const;
76 
77     /** Copy into 'parameters' (allocated by the caller) the design variation parameters.
78      *
79      *  @param parameters the buffer into which to write the design variation parameters.
80      *  @param coordinateCount the number of entries available through 'parameters'.
81      *
82      *  @return The number of axes, or -1 if there is an error.
83      *  If 'parameters != nullptr' and 'parameterCount >= numAxes' then 'parameters' will be
84      *  filled with the variation parameters describing the position of this typeface in design
85      *  variation space. It is possible the number of axes can be retrieved but actual parameters
86      *  cannot.
87      */
88     int getVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],
89                                      int parameterCount) const;
90 
91     /** Return a 32bit value for this typeface, unique for the underlying font
92         data. Will never return 0.
93      */
uniqueID()94     SkFontID uniqueID() const { return fUniqueID; }
95 
96     /** Return the uniqueID for the specified typeface. If the face is null,
97         resolve it to the default font and return its uniqueID. Will never
98         return 0.
99     */
100     static SkFontID UniqueID(const SkTypeface* face);
101 
102     /** Returns true if the two typefaces reference the same underlying font,
103         handling either being null (treating null as the default font)
104      */
105     static bool Equal(const SkTypeface* facea, const SkTypeface* faceb);
106 
107     /** Returns the default normal typeface, which is never nullptr. */
108     static sk_sp<SkTypeface> MakeDefault();
109 
110     /** Creates a new reference to the typeface that most closely matches the
111         requested familyName and fontStyle. This method allows extended font
112         face specifiers as in the SkFontStyle type. Will never return null.
113 
114         @param familyName  May be NULL. The name of the font family.
115         @param fontStyle   The style of the typeface.
116         @return reference to the closest-matching typeface. Call must call
117               unref() when they are done.
118     */
119     static sk_sp<SkTypeface> MakeFromName(const char familyName[], SkFontStyle fontStyle);
120 
121     /** Return a new typeface given a file. If the file does not exist, or is
122         not a valid font file, returns nullptr.
123     */
124     static sk_sp<SkTypeface> MakeFromFile(const char path[], int index = 0);
125 
126     /** Return a new typeface given a stream. If the stream is
127         not a valid font file, returns nullptr. Ownership of the stream is
128         transferred, so the caller must not reference it again.
129     */
130     static sk_sp<SkTypeface> MakeFromStream(std::unique_ptr<SkStreamAsset> stream, int index = 0);
131 
132     /** Return a new typeface given a SkData. If the data is null, or is not a valid font file,
133      *  returns nullptr.
134      */
135     static sk_sp<SkTypeface> MakeFromData(sk_sp<SkData>, int index = 0);
136 
137     /** Return a new typeface given font data and configuration. If the data
138         is not valid font data, returns nullptr.
139     */
140     static sk_sp<SkTypeface> MakeFromFontData(std::unique_ptr<SkFontData>);
141 
142     /** Return a new typeface based on this typeface but parameterized as specified in the
143         SkFontArguments. If the SkFontArguments does not supply an argument for a parameter
144         in the font then the value from this typeface will be used as the value for that
145         argument. If the cloned typeface would be exaclty the same as this typeface then
146         this typeface may be ref'ed and returned. May return nullptr on failure.
147     */
148     sk_sp<SkTypeface> makeClone(const SkFontArguments&) const;
149 
150     /**
151      *  A typeface can serialize just a descriptor (names, etc.), or it can also include the
152      *  actual font data (which can be large). This enum controls how serialize() decides what
153      *  to serialize.
154      */
155     enum class SerializeBehavior {
156         kDoIncludeData,
157         kDontIncludeData,
158         kIncludeDataIfLocal,
159     };
160 
161     /** Write a unique signature to a stream, sufficient to reconstruct a
162         typeface referencing the same font when Deserialize is called.
163      */
164     void serialize(SkWStream*, SerializeBehavior = SerializeBehavior::kIncludeDataIfLocal) const;
165 
166     /**
167      *  Same as serialize(SkWStream*, ...) but returns the serialized data in SkData, instead of
168      *  writing it to a stream.
169      */
170     sk_sp<SkData> serialize(SerializeBehavior = SerializeBehavior::kIncludeDataIfLocal) const;
171 
172     /** Given the data previously written by serialize(), return a new instance
173         of a typeface referring to the same font. If that font is not available,
174         return nullptr.
175         Does not affect ownership of SkStream.
176      */
177     static sk_sp<SkTypeface> MakeDeserialize(SkStream*);
178 
179     enum Encoding : uint8_t {
180         kUTF8_Encoding,
181         kUTF16_Encoding,
182         kUTF32_Encoding
183     };
184 
185     /**
186      *  Given an array of character codes, of the specified encoding,
187      *  optionally return their corresponding glyph IDs (if glyphs is not NULL).
188      *
189      *  @param chars pointer to the array of character codes
190      *  @param encoding how the characters are encoded
191      *  @param glyphs (optional) returns the corresponding glyph IDs for each
192      *          character code, up to glyphCount values. If a character code is
193      *          not found in the typeface, the corresponding glyph ID will be 0.
194      *  @param glyphCount number of code points in 'chars' to process. If glyphs
195      *          is not NULL, then it must point sufficient memory to write
196      *          glyphCount values into it.
197      *  @return the number of number of continuous non-zero glyph IDs computed
198      *          from the beginning of chars. This value is valid, even if the
199      *          glyphs parameter is NULL.
200      */
201     int charsToGlyphs(const void* chars, Encoding encoding, SkGlyphID glyphs[],
202                       int glyphCount) const;
203 
204     /**
205      *  Return the glyphID that corresponds to the specified unicode code-point
206      *  (in UTF32 encoding). If the unichar is not supported, returns 0.
207      *
208      *  This is a short-cut for calling charsToGlyphs() with kUTF32_Encoding for one code-point.
209      */
210     SkGlyphID unicharToGlyph(SkUnichar unichar) const;
211 
212     /**
213      *  Return the number of glyphs in the typeface.
214      */
215     int countGlyphs() const;
216 
217     // Table getters -- may fail if the underlying font format is not organized
218     // as 4-byte tables.
219 
220     /** Return the number of tables in the font. */
221     int countTables() const;
222 
223     /** Copy into tags[] (allocated by the caller) the list of table tags in
224      *  the font, and return the number. This will be the same as CountTables()
225      *  or 0 if an error occured. If tags == NULL, this only returns the count
226      *  (the same as calling countTables()).
227      */
228     int getTableTags(SkFontTableTag tags[]) const;
229 
230     /** Given a table tag, return the size of its contents, or 0 if not present
231      */
232     size_t getTableSize(SkFontTableTag) const;
233 
234     /** Copy the contents of a table into data (allocated by the caller). Note
235      *  that the contents of the table will be in their native endian order
236      *  (which for most truetype tables is big endian). If the table tag is
237      *  not found, or there is an error copying the data, then 0 is returned.
238      *  If this happens, it is possible that some or all of the memory pointed
239      *  to by data may have been written to, even though an error has occured.
240      *
241      *  @param fontID the font to copy the table from
242      *  @param tag  The table tag whose contents are to be copied
243      *  @param offset The offset in bytes into the table's contents where the
244      *  copy should start from.
245      *  @param length The number of bytes, starting at offset, of table data
246      *  to copy.
247      *  @param data storage address where the table contents are copied to
248      *  @return the number of bytes actually copied into data. If offset+length
249      *  exceeds the table's size, then only the bytes up to the table's
250      *  size are actually copied, and this is the value returned. If
251      *  offset > the table's size, or tag is not a valid table,
252      *  then 0 is returned.
253      */
254     size_t getTableData(SkFontTableTag tag, size_t offset, size_t length,
255                         void* data) const;
256 
257     /**
258      *  Return the units-per-em value for this typeface, or zero if there is an
259      *  error.
260      */
261     int getUnitsPerEm() const;
262 
263     /**
264      *  Given a run of glyphs, return the associated horizontal adjustments.
265      *  Adjustments are in "design units", which are integers relative to the
266      *  typeface's units per em (see getUnitsPerEm).
267      *
268      *  Some typefaces are known to never support kerning. Calling this method
269      *  with all zeros (e.g. getKerningPairAdustments(NULL, 0, NULL)) returns
270      *  a boolean indicating if the typeface might support kerning. If it
271      *  returns false, then it will always return false (no kerning) for all
272      *  possible glyph runs. If it returns true, then it *may* return true for
273      *  somne glyph runs.
274      *
275      *  If count is non-zero, then the glyphs parameter must point to at least
276      *  [count] valid glyph IDs, and the adjustments parameter must be
277      *  sized to at least [count - 1] entries. If the method returns true, then
278      *  [count-1] entries in the adjustments array will be set. If the method
279      *  returns false, then no kerning should be applied, and the adjustments
280      *  array will be in an undefined state (possibly some values may have been
281      *  written, but none of them should be interpreted as valid values).
282      */
283     bool getKerningPairAdjustments(const SkGlyphID glyphs[], int count,
284                                    int32_t adjustments[]) const;
285 
286     struct LocalizedString {
287         SkString fString;
288         SkString fLanguage;
289     };
290     class LocalizedStrings : ::SkNoncopyable {
291     public:
~LocalizedStrings()292         virtual ~LocalizedStrings() { }
293         virtual bool next(LocalizedString* localizedString) = 0;
unref()294         void unref() { delete this; }
295     };
296     /**
297      *  Returns an iterator which will attempt to enumerate all of the
298      *  family names specified by the font.
299      *  It is the caller's responsibility to unref() the returned pointer.
300      */
301     LocalizedStrings* createFamilyNameIterator() const;
302 
303     /**
304      *  Return the family name for this typeface. It will always be returned
305      *  encoded as UTF8, but the language of the name is whatever the host
306      *  platform chooses.
307      */
308     void getFamilyName(SkString* name) const;
309 
310     /**
311      *  Return a stream for the contents of the font data, or NULL on failure.
312      *  If ttcIndex is not null, it is set to the TrueTypeCollection index
313      *  of this typeface within the stream, or 0 if the stream is not a
314      *  collection.
315      *  The caller is responsible for deleting the stream.
316      */
317     SkStreamAsset* openStream(int* ttcIndex) const;
318 
319     /**
320      *  Return the font data, or nullptr on failure.
321      */
322     std::unique_ptr<SkFontData> makeFontData() const;
323 
324     /**
325      *  Return a scalercontext for the given descriptor. If this fails, then
326      *  if allowFailure is true, this returns NULL, else it returns a
327      *  dummy scalercontext that will not crash, but will draw nothing.
328      */
329     std::unique_ptr<SkScalerContext> createScalerContext(const SkScalerContextEffects&,
330                                                          const SkDescriptor*,
331                                                          bool allowFailure = false) const;
332 
333     /**
334      *  Return a rectangle (scaled to 1-pt) that represents the union of the bounds of all
335      *  of the glyphs, but each one positioned at (0,). This may be conservatively large, and
336      *  will not take into account any hinting or other size-specific adjustments.
337      */
338     SkRect getBounds() const;
339 
340     // PRIVATE / EXPERIMENTAL -- do not call
filterRec(SkScalerContextRec * rec)341     void filterRec(SkScalerContextRec* rec) const {
342         this->onFilterRec(rec);
343     }
344     // PRIVATE / EXPERIMENTAL -- do not call
getFontDescriptor(SkFontDescriptor * desc,bool * isLocal)345     void getFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const {
346         this->onGetFontDescriptor(desc, isLocal);
347     }
348     // PRIVATE / EXPERIMENTAL -- do not call
internal_private_getCTFontRef()349     void* internal_private_getCTFontRef() const {
350         return this->onGetCTFontRef();
351     }
352 
353 protected:
354     /** uniqueID must be unique and non-zero
355     */
356     SkTypeface(const SkFontStyle& style, bool isFixedPitch = false);
357     virtual ~SkTypeface();
358 
359     virtual sk_sp<SkTypeface> onMakeClone(const SkFontArguments&) const;
360 
361     /** Sets the fixedPitch bit. If used, must be called in the constructor. */
setIsFixedPitch(bool isFixedPitch)362     void setIsFixedPitch(bool isFixedPitch) { fIsFixedPitch = isFixedPitch; }
363     /** Sets the font style. If used, must be called in the constructor. */
setFontStyle(SkFontStyle style)364     void setFontStyle(SkFontStyle style) { fStyle = style; }
365 
366     virtual SkScalerContext* onCreateScalerContext(const SkScalerContextEffects&,
367                                                    const SkDescriptor*) const = 0;
368     virtual void onFilterRec(SkScalerContextRec*) const = 0;
369     friend class SkScalerContext;  // onFilterRec
370 
371     //  Subclasses *must* override this method to work with the PDF backend.
372     virtual std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const;
373     // For type1 postscript fonts only, set the glyph names for each glyph.
374     // destination array is non-null, and points to an array of size this->countGlyphs().
375     // Backends that do not suport type1 fonts should not override.
getPostScriptGlyphNames(SkString *)376     virtual void getPostScriptGlyphNames(SkString*) const {}
377 
378     // The mapping from glyph to Unicode; array indices are glyph ids.
379     // For each glyph, give the default Unicode value, if it exists.
380     // dstArray is non-null, and points to an array of size this->countGlyphs().
381     virtual void getGlyphToUnicodeMap(SkUnichar* dstArray) const;
382 
383     virtual SkStreamAsset* onOpenStream(int* ttcIndex) const = 0;
384     // TODO: make pure virtual.
385     virtual std::unique_ptr<SkFontData> onMakeFontData() const;
386 
387     virtual int onGetVariationDesignPosition(
388         SkFontArguments::VariationPosition::Coordinate coordinates[],
389         int coordinateCount) const = 0;
390 
391     virtual int onGetVariationDesignParameters(
392         SkFontParameters::Variation::Axis parameters[], int parameterCount) const;
393 
394     virtual void onGetFontDescriptor(SkFontDescriptor*, bool* isLocal) const = 0;
395 
396     virtual int onCharsToGlyphs(const void* chars, Encoding, SkGlyphID glyphs[],
397                                 int glyphCount) const = 0;
398     virtual int onCountGlyphs() const = 0;
399 
400     virtual int onGetUPEM() const = 0;
401     virtual bool onGetKerningPairAdjustments(const SkGlyphID glyphs[], int count,
402                                              int32_t adjustments[]) const;
403 
404     /** Returns the family name of the typeface as known by its font manager.
405      *  This name may or may not be produced by the family name iterator.
406      */
407     virtual void onGetFamilyName(SkString* familyName) const = 0;
408 
409     /** Returns an iterator over the family names in the font. */
410     virtual LocalizedStrings* onCreateFamilyNameIterator() const = 0;
411 
412     virtual int onGetTableTags(SkFontTableTag tags[]) const = 0;
413     virtual size_t onGetTableData(SkFontTableTag, size_t offset,
414                                   size_t length, void* data) const = 0;
415 
416     virtual bool onComputeBounds(SkRect*) const;
417 
onGetCTFontRef()418     virtual void* onGetCTFontRef() const { return nullptr; }
419 
420 private:
421     /** Retrieve detailed typeface metrics.  Used by the PDF backend.  */
422     std::unique_ptr<SkAdvancedTypefaceMetrics> getAdvancedMetrics() const;
423     friend class SkRandomTypeface; // getAdvancedMetrics
424     friend class SkPDFFont;        // getAdvancedMetrics
425 
426     /** Style specifies the intrinsic style attributes of a given typeface */
427     enum Style {
428         kNormal = 0,
429         kBold   = 0x01,
430         kItalic = 0x02,
431 
432         // helpers
433         kBoldItalic = 0x03
434     };
435     static SkFontStyle FromOldStyle(Style oldStyle);
436     static SkTypeface* GetDefaultTypeface(Style style = SkTypeface::kNormal);
437 
438     friend class SkFontPriv;       // GetDefaultTypeface
439     friend class SkPaintPriv;      // GetDefaultTypeface
440     friend class SkFont;           // getGlyphToUnicodeMap
441 
442 private:
443     SkFontID            fUniqueID;
444     SkFontStyle         fStyle;
445     mutable SkRect      fBounds;
446     mutable SkOnce      fBoundsOnce;
447     bool                fIsFixedPitch;
448 
449     typedef SkWeakRefCnt INHERITED;
450 };
451 #endif
452