• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "include/core/SkFontArguments.h"
12 #include "include/core/SkFontParameters.h"
13 #include "include/core/SkFontStyle.h"
14 #include "include/core/SkFontTypes.h"
15 #include "include/core/SkRect.h"
16 #include "include/core/SkString.h"
17 #include "include/private/SkOnce.h"
18 #include "include/private/SkWeakRefCnt.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 based on this typeface but parameterized as specified in the
138         SkFontArguments. If the SkFontArguments does not supply an argument for a parameter
139         in the font then the value from this typeface will be used as the value for that
140         argument. If the cloned typeface would be exaclty the same as this typeface then
141         this typeface may be ref'ed and returned. May return nullptr on failure.
142     */
143     sk_sp<SkTypeface> makeClone(const SkFontArguments&) const;
144 
145     /**
146      *  A typeface can serialize just a descriptor (names, etc.), or it can also include the
147      *  actual font data (which can be large). This enum controls how serialize() decides what
148      *  to serialize.
149      */
150     enum class SerializeBehavior {
151         kDoIncludeData,
152         kDontIncludeData,
153         kIncludeDataIfLocal,
154     };
155 
156     /** Write a unique signature to a stream, sufficient to reconstruct a
157         typeface referencing the same font when Deserialize is called.
158      */
159     void serialize(SkWStream*, SerializeBehavior = SerializeBehavior::kIncludeDataIfLocal) const;
160 
161     /**
162      *  Same as serialize(SkWStream*, ...) but returns the serialized data in SkData, instead of
163      *  writing it to a stream.
164      */
165     sk_sp<SkData> serialize(SerializeBehavior = SerializeBehavior::kIncludeDataIfLocal) const;
166 
167     /** Given the data previously written by serialize(), return a new instance
168         of a typeface referring to the same font. If that font is not available,
169         return nullptr.
170         Does not affect ownership of SkStream.
171      */
172     static sk_sp<SkTypeface> MakeDeserialize(SkStream*);
173 
174     /**
175      *  Given an array of UTF32 character codes, return their corresponding glyph IDs.
176      *
177      *  @param chars pointer to the array of UTF32 chars
178      *  @param number of chars and glyphs
179      *  @param glyphs returns the corresponding glyph IDs for each character.
180      */
181     void unicharsToGlyphs(const SkUnichar uni[], int count, SkGlyphID glyphs[]) const;
182 
183     int textToGlyphs(const void* text, size_t byteLength, SkTextEncoding encoding,
184                      SkGlyphID glyphs[], int maxGlyphCount) const;
185 
186     /**
187      *  Return the glyphID that corresponds to the specified unicode code-point
188      *  (in UTF32 encoding). If the unichar is not supported, returns 0.
189      *
190      *  This is a short-cut for calling unicharsToGlyphs().
191      */
192     SkGlyphID unicharToGlyph(SkUnichar unichar) const;
193 
194     /**
195      *  Return the number of glyphs in the typeface.
196      */
197     int countGlyphs() const;
198 
199     // Table getters -- may fail if the underlying font format is not organized
200     // as 4-byte tables.
201 
202     /** Return the number of tables in the font. */
203     int countTables() const;
204 
205     /** Copy into tags[] (allocated by the caller) the list of table tags in
206      *  the font, and return the number. This will be the same as CountTables()
207      *  or 0 if an error occured. If tags == NULL, this only returns the count
208      *  (the same as calling countTables()).
209      */
210     int getTableTags(SkFontTableTag tags[]) const;
211 
212     /** Given a table tag, return the size of its contents, or 0 if not present
213      */
214     size_t getTableSize(SkFontTableTag) const;
215 
216     /** Copy the contents of a table into data (allocated by the caller). Note
217      *  that the contents of the table will be in their native endian order
218      *  (which for most truetype tables is big endian). If the table tag is
219      *  not found, or there is an error copying the data, then 0 is returned.
220      *  If this happens, it is possible that some or all of the memory pointed
221      *  to by data may have been written to, even though an error has occured.
222      *
223      *  @param tag  The table tag whose contents are to be copied
224      *  @param offset The offset in bytes into the table's contents where the
225      *  copy should start from.
226      *  @param length The number of bytes, starting at offset, of table data
227      *  to copy.
228      *  @param data storage address where the table contents are copied to
229      *  @return the number of bytes actually copied into data. If offset+length
230      *  exceeds the table's size, then only the bytes up to the table's
231      *  size are actually copied, and this is the value returned. If
232      *  offset > the table's size, or tag is not a valid table,
233      *  then 0 is returned.
234      */
235     size_t getTableData(SkFontTableTag tag, size_t offset, size_t length,
236                         void* data) const;
237 
238     /**
239      *  Return an immutable copy of the requested font table, or nullptr if that table was
240      *  not found. This can sometimes be faster than calling getTableData() twice: once to find
241      *  the length, and then again to copy the data.
242      *
243      *  @param tag  The table tag whose contents are to be copied
244      *  @return an immutable copy of the table's data, or nullptr.
245      */
246     sk_sp<SkData> copyTableData(SkFontTableTag tag) const;
247 
248     /**
249      *  Return the units-per-em value for this typeface, or zero if there is an
250      *  error.
251      */
252     int getUnitsPerEm() const;
253 
254     /**
255      *  Given a run of glyphs, return the associated horizontal adjustments.
256      *  Adjustments are in "design units", which are integers relative to the
257      *  typeface's units per em (see getUnitsPerEm).
258      *
259      *  Some typefaces are known to never support kerning. Calling this method
260      *  with all zeros (e.g. getKerningPairAdustments(NULL, 0, NULL)) returns
261      *  a boolean indicating if the typeface might support kerning. If it
262      *  returns false, then it will always return false (no kerning) for all
263      *  possible glyph runs. If it returns true, then it *may* return true for
264      *  somne glyph runs.
265      *
266      *  If count is non-zero, then the glyphs parameter must point to at least
267      *  [count] valid glyph IDs, and the adjustments parameter must be
268      *  sized to at least [count - 1] entries. If the method returns true, then
269      *  [count-1] entries in the adjustments array will be set. If the method
270      *  returns false, then no kerning should be applied, and the adjustments
271      *  array will be in an undefined state (possibly some values may have been
272      *  written, but none of them should be interpreted as valid values).
273      */
274     bool getKerningPairAdjustments(const SkGlyphID glyphs[], int count,
275                                    int32_t adjustments[]) const;
276 
277     struct LocalizedString {
278         SkString fString;
279         SkString fLanguage;
280     };
281     class LocalizedStrings {
282     public:
283         LocalizedStrings() = default;
~LocalizedStrings()284         virtual ~LocalizedStrings() { }
285         virtual bool next(LocalizedString* localizedString) = 0;
unref()286         void unref() { delete this; }
287 
288     private:
289         LocalizedStrings(const LocalizedStrings&) = delete;
290         LocalizedStrings& operator=(const LocalizedStrings&) = delete;
291     };
292     /**
293      *  Returns an iterator which will attempt to enumerate all of the
294      *  family names specified by the font.
295      *  It is the caller's responsibility to unref() the returned pointer.
296      */
297     LocalizedStrings* createFamilyNameIterator() const;
298 
299     /**
300      *  Return the family name for this typeface. It will always be returned
301      *  encoded as UTF8, but the language of the name is whatever the host
302      *  platform chooses.
303      */
304     void getFamilyName(SkString* name) const;
305 
306     /**
307      *  Return the PostScript name for this typeface.
308      *  Value may change based on variation parameters.
309      *  Returns false if no PostScript name is available.
310      */
311     bool getPostScriptName(SkString* name) const;
312 
313     /**
314      *  Return a stream for the contents of the font data, or NULL on failure.
315      *  If ttcIndex is not null, it is set to the TrueTypeCollection index
316      *  of this typeface within the stream, or 0 if the stream is not a
317      *  collection.
318      *  The caller is responsible for deleting the stream.
319      */
320     std::unique_ptr<SkStreamAsset> openStream(int* ttcIndex) const;
321 
322     /**
323      * Return a stream for the contents of the font data.
324      * Returns nullptr on failure or if the font data isn't already available in stream form.
325      * Use when the stream can be used opportunistically but the calling code would prefer
326      * to fall back to table access if creating the stream would be expensive.
327      * Otherwise acts the same as openStream.
328      */
329     std::unique_ptr<SkStreamAsset> openExistingStream(int* ttcIndex) const;
330 
331     /**
332      *  Return a scalercontext for the given descriptor. It may return a
333      *  stub scalercontext that will not crash, but will draw nothing.
334      */
335     std::unique_ptr<SkScalerContext> createScalerContext(const SkScalerContextEffects&,
336                                                          const SkDescriptor*) const;
337 
338     /**
339      *  Return a rectangle (scaled to 1-pt) that represents the union of the bounds of all
340      *  of the glyphs, but each one positioned at (0,). This may be conservatively large, and
341      *  will not take into account any hinting or other size-specific adjustments.
342      */
343     SkRect getBounds() const;
344 
345     bool isCustomTypeface() const;
346     void setIsCustomTypeface(bool isCustom);
347 
348     // PRIVATE / EXPERIMENTAL -- do not call
filterRec(SkScalerContextRec * rec)349     void filterRec(SkScalerContextRec* rec) const {
350         this->onFilterRec(rec);
351     }
352     // PRIVATE / EXPERIMENTAL -- do not call
getFontDescriptor(SkFontDescriptor * desc,bool * isLocal)353     void getFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const {
354         this->onGetFontDescriptor(desc, isLocal);
355     }
356     // PRIVATE / EXPERIMENTAL -- do not call
internal_private_getCTFontRef()357     void* internal_private_getCTFontRef() const {
358         return this->onGetCTFontRef();
359     }
360 
361 protected:
362     explicit SkTypeface(const SkFontStyle& style, bool isFixedPitch = false);
363     ~SkTypeface() override;
364 
365     virtual sk_sp<SkTypeface> onMakeClone(const SkFontArguments&) const = 0;
366 
367     /** Sets the fixedPitch bit. If used, must be called in the constructor. */
setIsFixedPitch(bool isFixedPitch)368     void setIsFixedPitch(bool isFixedPitch) { fIsFixedPitch = isFixedPitch; }
369     /** Sets the font style. If used, must be called in the constructor. */
setFontStyle(SkFontStyle style)370     void setFontStyle(SkFontStyle style) { fStyle = style; }
371 
372     // Must return a valid scaler context. It can not return nullptr.
373     virtual std::unique_ptr<SkScalerContext> onCreateScalerContext(const SkScalerContextEffects&,
374                                                                    const SkDescriptor*) const = 0;
375     virtual void onFilterRec(SkScalerContextRec*) const = 0;
376     friend class SkScalerContext;  // onFilterRec
377 
378     //  Subclasses *must* override this method to work with the PDF backend.
379     virtual std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const = 0;
380     // For type1 postscript fonts only, set the glyph names for each glyph.
381     // destination array is non-null, and points to an array of size this->countGlyphs().
382     // Backends that do not suport type1 fonts should not override.
383     virtual void getPostScriptGlyphNames(SkString*) const = 0;
384 
385     // The mapping from glyph to Unicode; array indices are glyph ids.
386     // For each glyph, give the default Unicode value, if it exists.
387     // dstArray is non-null, and points to an array of size this->countGlyphs().
388     virtual void getGlyphToUnicodeMap(SkUnichar* dstArray) const = 0;
389 
390     virtual std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const = 0;
391 
392     virtual std::unique_ptr<SkStreamAsset> onOpenExistingStream(int* ttcIndex) const;
393 
394     virtual bool onGlyphMaskNeedsCurrentColor() const = 0;
395 
396     virtual int onGetVariationDesignPosition(
397         SkFontArguments::VariationPosition::Coordinate coordinates[],
398         int coordinateCount) const = 0;
399 
400     virtual int onGetVariationDesignParameters(
401         SkFontParameters::Variation::Axis parameters[], int parameterCount) const = 0;
402 
403     virtual void onGetFontDescriptor(SkFontDescriptor*, bool* isLocal) const = 0;
404 
405     virtual void onCharsToGlyphs(const SkUnichar* chars, int count, SkGlyphID glyphs[]) const = 0;
406     virtual int onCountGlyphs() const = 0;
407 
408     virtual int onGetUPEM() const = 0;
409     virtual bool onGetKerningPairAdjustments(const SkGlyphID glyphs[], int count,
410                                              int32_t adjustments[]) const;
411 
412     /** Returns the family name of the typeface as known by its font manager.
413      *  This name may or may not be produced by the family name iterator.
414      */
415     virtual void onGetFamilyName(SkString* familyName) const = 0;
416     virtual bool onGetPostScriptName(SkString*) const = 0;
417 
418     /** Returns an iterator over the family names in the font. */
419     virtual LocalizedStrings* onCreateFamilyNameIterator() const = 0;
420 
421     virtual int onGetTableTags(SkFontTableTag tags[]) const = 0;
422     virtual size_t onGetTableData(SkFontTableTag, size_t offset,
423                                   size_t length, void* data) const = 0;
424     virtual sk_sp<SkData> onCopyTableData(SkFontTableTag) const;
425 
426     virtual bool onComputeBounds(SkRect*) const;
427 
onGetCTFontRef()428     virtual void* onGetCTFontRef() const { return nullptr; }
429 
430 private:
431     /** Returns true if the typeface's glyph masks may refer to the foreground
432      *  paint foreground color. This is needed to determine caching requirements. Usually true for
433      *  typefaces that contain a COLR table.
434      */
435     bool glyphMaskNeedsCurrentColor() const;
436     friend class SkStrikeServerImpl; // glyphMaskNeedsCurrentColor
437 
438     /** Retrieve detailed typeface metrics.  Used by the PDF backend.  */
439     std::unique_ptr<SkAdvancedTypefaceMetrics> getAdvancedMetrics() const;
440     friend class SkRandomTypeface;   // getAdvancedMetrics
441     friend class SkPDFFont;          // getAdvancedMetrics
442 
443     /** Style specifies the intrinsic style attributes of a given typeface */
444     enum Style {
445         kNormal = 0,
446         kBold   = 0x01,
447         kItalic = 0x02,
448 
449         // helpers
450         kBoldItalic = 0x03
451     };
452     static SkFontStyle FromOldStyle(Style oldStyle);
453     static SkTypeface* GetDefaultTypeface(Style style = SkTypeface::kNormal);
454 
455     friend class SkFontPriv;         // GetDefaultTypeface
456     friend class SkPaintPriv;        // GetDefaultTypeface
457     friend class SkFont;             // getGlyphToUnicodeMap
458 
459 private:
460     SkFontID            fUniqueID;
461     SkFontStyle         fStyle;
462     mutable SkRect      fBounds;
463     mutable SkOnce      fBoundsOnce;
464     bool                fIsFixedPitch;
465     bool                fIsCustom = false;
466 
467     using INHERITED = SkWeakRefCnt;
468 };
469 #endif
470