Debian Codegraph @

include/core/SkTypeface.h

raw
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/SkFourByteTag.h"
15 #include "include/core/SkRect.h"
16 #include "include/core/SkRefCnt.h"
17 #include "include/core/SkSpan.h"
18 #include "include/core/SkString.h"
19 #include "include/core/SkTypes.h"
20 #include "include/private/SkWeakRefCnt.h"
21 #include "include/private/base/SkOnce.h"
22
23 #include <cstddef>
24 #include <cstdint>
25 #include <memory>
26
27 class SkData;
28 class SkDescriptor;
29 class SkFontMgr;
30 class SkFontDescriptor;
31 class SkScalerContext;
32 class SkStream;
33 class SkStreamAsset;
34 class SkWStream;
35 enum class SkTextEncoding;
36 struct SkAdvancedTypefaceMetrics;
37 struct SkScalerContextEffects;
38 struct SkScalerContextRec;
39
40 using SkTypefaceID = uint32_t;
41
42 /** Machine endian. */
43 typedef uint32_t SkFontTableTag;
44
45 /** \class SkTypeface
46
47 The SkTypeface class specifies the typeface and intrinsic style of a font.
48 This is used in the paint, along with optionally algorithmic settings like
49 textSize, textSkewX, textScaleX, kFakeBoldText_Mask, to specify
50 how text appears when drawn (and measured).
51
52 Typeface objects are immutable, and so they can be shared between threads.
53 */
54 class SK_API SkTypeface : public SkWeakRefCnt {
55 public:
56 /** Returns the typeface's intrinsic style attributes. */
57 SkFontStyle fontStyle() const;
58
59 /** Returns true if fontStyle() weight is at least semi bold */
60 bool isBold() const;
61
62 /** Returns true if fontStyle() is not upright. */
63 bool isItalic() const;
64
65 /** Returns true if the typeface claims to be fixed-pitch.
66 * This is a style bit, advance widths may vary even if this returns true.
67 */
68 bool isFixedPitch() const;
69
70 /** Copy into 'coordinates' (allocated by the caller) the design variation coordinates.
71 *
72 * @param coordinates the span into which to write the design variation coordinates.
73 *
74 * @return The number of axes, or -1 if there is an error.
75 * If 'coordinates.size() >= numAxes' then 'coordinates' will be
76 * filled with the variation coordinates describing the position of this typeface in design
77 * variation space. It is possible the number of axes can be retrieved but actual position
78 * cannot.
79 */
80 int getVariationDesignPosition(
81 SkSpan<SkFontArguments::VariationPosition::Coordinate> coordinates) const;
82
83 /** Copy into 'parameters' (allocated by the caller) the design variation parameters.
84 *
85 * @param parameters the span into which to write the design variation parameters.
86 *
87 * @return The number of axes, or -1 if there is an error.
88 * If 'parameters.size() >= numAxes' then 'parameters' will be
89 * filled with the variation parameters describing the position of this typeface in design
90 * variation space. It is possible the number of axes can be retrieved but actual parameters
91 * cannot.
92 */
93 int getVariationDesignParameters(SkSpan<SkFontParameters::Variation::Axis> parameters) const;
94
95 /** Returns true if the typeface is internally being fake bolded. */
96 bool isSyntheticBold() const;
97
98 /** Returns true if the typeface is internally being fake obliqued. */
99 bool isSyntheticOblique() const;
100
101 /** Return a 32bit value for this typeface, unique for the underlying font
102 data. Will never return 0.
103 */
104 SkTypefaceID uniqueID() const { return fUniqueID; }
105
106 /** Returns true if the two typefaces reference the same underlying font,
107 handling either being null (treating null as not equal to any font).
108 */
109 static bool Equal(const SkTypeface* facea, const SkTypeface* faceb);
110
111 /** Returns a non-null typeface which contains no glyphs. */
112 static sk_sp<SkTypeface> MakeEmpty();
113
114 /** Return a new typeface based on this typeface but parameterized as specified in the
115 SkFontArguments. If the SkFontArguments does not supply an argument for a parameter
116 in the font then the value from this typeface will be used as the value for that
117 argument. If the cloned typeface would be exaclty the same as this typeface then
118 this typeface may be ref'ed and returned. May return nullptr on failure.
119 */
120 sk_sp<SkTypeface> makeClone(const SkFontArguments&) const;
121
122 /**
123 * A typeface can serialize just a descriptor (names, etc.), or it can also include the
124 * actual font data (which can be large). This enum controls how serialize() decides what
125 * to serialize.
126 */
127 enum class SerializeBehavior {
128 kDoIncludeData,
129 kDontIncludeData,
130 kIncludeDataIfLocal,
131 };
132
133 /** Write a unique signature to a stream, sufficient to reconstruct a
134 typeface referencing the same font when Deserialize is called.
135 */
136 bool serialize(SkWStream*, SerializeBehavior = SerializeBehavior::kIncludeDataIfLocal) const;
137
138 /**
139 * Same as serialize(SkWStream*, ...) but returns the serialized data in SkData, instead of
140 * writing it to a stream.
141 */
142 sk_sp<SkData> serialize(SerializeBehavior = SerializeBehavior::kIncludeDataIfLocal) const;
143
144 /** Given the data previously written by serialize(), return a new instance
145 of a typeface referring to the same font. If that font is not available,
146 return nullptr.
147 Goes through all registered typeface factories and lastResortMgr (if non-null).
148 Does not affect ownership of SkStream.
149 */
150
151 static sk_sp<SkTypeface> MakeDeserialize(SkStream*, sk_sp<SkFontMgr> lastResortMgr);
152
153 /**
154 * Given an array of UTF32 character codes, return their corresponding glyph IDs.
155 *
156 * @param unis span of UTF32 chars
157 * @param glyphs returns the corresponding glyph IDs for each character.
158 */
159 void unicharsToGlyphs(SkSpan<const SkUnichar> unis, SkSpan<SkGlyphID> glyphs) const;
160
161 size_t textToGlyphs(const void* text, size_t byteLength, SkTextEncoding encoding,
162 SkSpan<SkGlyphID> glyphs) const;
163
164 /**
165 * Return the glyphID that corresponds to the specified unicode code-point
166 * (in UTF32 encoding). If the unichar is not supported, returns 0.
167 *
168 * This is a short-cut for calling unicharsToGlyphs().
169 */
170 SkGlyphID unicharToGlyph(SkUnichar unichar) const;
171
172 /**
173 * Return the number of glyphs in the typeface.
174 */
175 int countGlyphs() const;
176
177 // Table getters -- may fail if the underlying font format is not organized
178 // as 4-byte tables.
179
180 /** Return the number of tables in the font. */
181 int countTables() const;
182
183 /** Copy into tags[] (allocated by the caller) the list of table tags in
184 * the font, and return the number. This will be the same as CountTables()
185 * or 0 if an error occured. If tags is empty, this only returns the count
186 * (the same as calling countTables()).
187 */
188 int readTableTags(SkSpan<SkFontTableTag> tags) const;
189
190 /** Given a table tag, return the size of its contents, or 0 if not present
191 */
192 size_t getTableSize(SkFontTableTag) const;
193
194 /** Copy the contents of a table into data (allocated by the caller). Note
195 * that the contents of the table will be in their native endian order
196 * (which for most truetype tables is big endian). If the table tag is
197 * not found, or there is an error copying the data, then 0 is returned.
198 * If this happens, it is possible that some or all of the memory pointed
199 * to by data may have been written to, even though an error has occured.
200 *
201 * @param tag The table tag whose contents are to be copied
202 * @param offset The offset in bytes into the table's contents where the
203 * copy should start from.
204 * @param length The number of bytes, starting at offset, of table data
205 * to copy.
206 * @param data storage address where the table contents are copied to
207 * @return the number of bytes actually copied into data. If offset+length
208 * exceeds the table's size, then only the bytes up to the table's
209 * size are actually copied, and this is the value returned. If
210 * offset > the table's size, or tag is not a valid table,
211 * then 0 is returned.
212 */
213 size_t getTableData(SkFontTableTag tag, size_t offset, size_t length,
214 void* data) const;
215
216 /**
217 * Return an immutable copy of the requested font table, or nullptr if that table was
218 * not found. This can sometimes be faster than calling getTableData() twice: once to find
219 * the length, and then again to copy the data.
220 *
221 * @param tag The table tag whose contents are to be copied
222 * @return an immutable copy of the table's data, or nullptr.
223 */
224 sk_sp<SkData> copyTableData(SkFontTableTag tag) const;
225
226 /**
227 * Return the units-per-em value for this typeface, or zero if there is an
228 * error.
229 */
230 int getUnitsPerEm() const;
231
232 /**
233 * Given a run of glyphs, return the associated horizontal adjustments.
234 * Adjustments are in "design units", which are integers relative to the
235 * typeface's units per em (see getUnitsPerEm).
236 *
237 * Some typefaces are known to never support kerning. Calling this method
238 * with empty spans (e.g. getKerningPairAdustments({}, {})) returns
239 * a boolean indicating if the typeface might support kerning. If it
240 * returns false, then it will always return false (no kerning) for all
241 * possible glyph runs. If it returns true, then it *may* return true for
242 * some glyph runs.
243 *
244 * If the method returns true, and there are 1 or more glyphs in the span, then
245 * this will return in adjustments N values,
246 * where N = min(glyphs.size() - 1, adjustments.size()).
247
248 * If the method returns false, then no kerning should be applied, and the adjustments
249 * array will be in an undefined state (possibly some values may have been
250 * written, but none of them should be interpreted as valid values).
251 */
252 bool getKerningPairAdjustments(SkSpan<const SkGlyphID> glyphs,
253 SkSpan<int32_t> adjustments) const;
254
255 struct LocalizedString {
256 SkString fString;
257 SkString fLanguage;
258 };
259 class LocalizedStrings {
260 public:
261 LocalizedStrings() = default;
262 virtual ~LocalizedStrings() { }
263 virtual bool next(LocalizedString* localizedString) = 0;
264 void unref() { delete this; }
265
266 private:
267 LocalizedStrings(const LocalizedStrings&) = delete;
268 LocalizedStrings& operator=(const LocalizedStrings&) = delete;
269 };
270 /**
271 * Returns an iterator which will attempt to enumerate all of the
272 * family names specified by the font.
273 * It is the caller's responsibility to unref() the returned pointer.
274 */
275 LocalizedStrings* createFamilyNameIterator() const;
276
277 /**
278 * Return the family name for this typeface. It will always be returned
279 * encoded as UTF8, but the language of the name is whatever the host
280 * platform chooses.
281 */
282 void getFamilyName(SkString* name) const;
283
284 /**
285 * Return the PostScript name for this typeface.
286 * Value may change based on variation parameters.
287 * Returns false if no PostScript name is available.
288 */
289 bool getPostScriptName(SkString* name) const;
290
291 /**
292 * If the primary resource backing this typeface has a name (like a file
293 * path or URL) representable by unicode code points, the `resourceName`
294 * will be set. The primary purpose is as a user facing indication about
295 * where the data was obtained (which font file was used).
296 *
297 * Returns the number of resources backing this typeface.
298 *
299 * For local font collections resource name will often be a file path. The
300 * file path may or may not exist. If it does exist, using it to create an
301 * SkTypeface may or may not create a similar SkTypeface to this one.
302 */
303 int getResourceName(SkString* resourceName) const;
304
305 /**
306 * Return a stream for the contents of the font data, or NULL on failure.
307 * If ttcIndex is not null, it is set to the TrueTypeCollection index
308 * of this typeface within the stream, or 0 if the stream is not a
309 * collection.
310 * The caller is responsible for deleting the stream.
311 */
312 std::unique_ptr<SkStreamAsset> openStream(int* ttcIndex) const;
313
314 /**
315 * Return a stream for the contents of the font data.
316 * Returns nullptr on failure or if the font data isn't already available in stream form.
317 * Use when the stream can be used opportunistically but the calling code would prefer
318 * to fall back to table access if creating the stream would be expensive.
319 * Otherwise acts the same as openStream.
320 */
321 std::unique_ptr<SkStreamAsset> openExistingStream(int* ttcIndex) const;
322
323 /**
324 * Return a scalercontext for the given descriptor. It may return a
325 * stub scalercontext that will not crash, but will draw nothing.
326 */
327 std::unique_ptr<SkScalerContext> createScalerContext(const SkScalerContextEffects&,
328 const SkDescriptor*) const;
329
330 /**
331 * Return a rectangle (scaled to 1-pt) that represents the union of the bounds of all
332 * of the glyphs, but each one positioned at (0,). This may be conservatively large, and
333 * will not take into account any hinting or other size-specific adjustments.
334 */
335 SkRect getBounds() const;
336
337 // PRIVATE / EXPERIMENTAL -- do not call
338 void filterRec(SkScalerContextRec* rec) const {
339 this->onFilterRec(rec);
340 }
341 // PRIVATE / EXPERIMENTAL -- do not call
342 void getFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const {
343 this->onGetFontDescriptor(desc, isLocal);
344 }
345 // PRIVATE / EXPERIMENTAL -- do not call
346 void* internal_private_getCTFontRef() const {
347 return this->onGetCTFontRef();
348 }
349
350 /* Skia reserves all tags that begin with a lower case letter and 0 */
351 using FactoryId = SkFourByteTag;
352 static void Register(
353 FactoryId id,
354 sk_sp<SkTypeface> (*make)(std::unique_ptr<SkStreamAsset>, const SkFontArguments&));
355
356 #ifdef SK_SUPPORT_UNSPANNED_APIS
357 public:
358 int getVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],
359 int count) const {
360 return this->getVariationDesignPosition({coordinates, count});
361 }
362 int getVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],
363 int count) const {
364 return this->getVariationDesignParameters({parameters, count});
365 }
366 void unicharsToGlyphs(const SkUnichar unis[], int count, SkGlyphID glyphs[]) const {
367 this->unicharsToGlyphs({unis, count}, {glyphs, count});
368 }
369 int textToGlyphs(const void* text, size_t byteLength, SkTextEncoding encoding,
370 SkGlyphID glyphs[], int maxGlyphCount) const {
371 return (int)this->textToGlyphs(text, byteLength, encoding, {glyphs, maxGlyphCount});
372 }
373 int getTableTags(SkFontTableTag tags[]) const {
374 const size_t count = tags ? MAX_REASONABLE_TABLE_COUNT : 0;
375 return this->readTableTags({tags, count});
376 }
377 bool getKerningPairAdjustments(const SkGlyphID glyphs[], int count,
378 int32_t adjustments[]) const {
379 return this->getKerningPairAdjustments({glyphs, count}, {adjustments, count});
380 }
381 #endif
382
383 protected:
384 // needed until onGetTableTags() is updated to take a span
385 enum { MAX_REASONABLE_TABLE_COUNT = (1 << 16) - 1 };
386
387 explicit SkTypeface(const SkFontStyle& style, bool isFixedPitch = false);
388 ~SkTypeface() override;
389
390 virtual sk_sp<SkTypeface> onMakeClone(const SkFontArguments&) const = 0;
391
392 /** Sets the fixedPitch bit. If used, must be called in the constructor. */
393 void setIsFixedPitch(bool isFixedPitch) { fIsFixedPitch = isFixedPitch; }
394 /** Sets the font style. If used, must be called in the constructor. */
395 void setFontStyle(SkFontStyle style) { fStyle = style; }
396
397 virtual SkFontStyle onGetFontStyle() const; // TODO: = 0;
398
399 virtual bool onGetFixedPitch() const; // TODO: = 0;
400
401 // Must return a valid scaler context. It can not return nullptr.
402 virtual std::unique_ptr<SkScalerContext> onCreateScalerContext(
403 const SkScalerContextEffects&, const SkDescriptor*) const = 0;
404 virtual std::unique_ptr<SkScalerContext> onCreateScalerContextAsProxyTypeface
405 (const SkScalerContextEffects&, const SkDescriptor*, SkTypeface* proxyTypeface) const;
406 virtual void onFilterRec(SkScalerContextRec*) const = 0;
407 friend class SkScalerContext; // onFilterRec
408
409 // Subclasses *must* override this method to work with the PDF backend.
410 virtual std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const = 0;
411 // For type1 postscript fonts only, set the glyph names for each glyph.
412 // destination array is non-null, and points to an array of size this->countGlyphs().
413 // Backends that do not suport type1 fonts should not override.
414 virtual void getPostScriptGlyphNames(SkString*) const = 0;
415
416 // The mapping from glyph to Unicode; array indices are glyph ids.
417 // For each glyph, give the default Unicode value, if it exists.
418 // dstArray is non-null, and points to an array of size this->countGlyphs().
419 virtual void getGlyphToUnicodeMap(SkSpan<SkUnichar> dstArray) const = 0;
420
421 virtual std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const = 0;
422
423 virtual std::unique_ptr<SkStreamAsset> onOpenExistingStream(int* ttcIndex) const;
424
425 virtual bool onGlyphMaskNeedsCurrentColor() const = 0;
426
427 virtual int onGetVariationDesignPosition(
428 SkSpan<SkFontArguments::VariationPosition::Coordinate>) const = 0;
429
430 virtual int onGetVariationDesignParameters(SkSpan<SkFontParameters::Variation::Axis>) const = 0;
431
432 virtual bool onIsSyntheticBold() const;
433 virtual bool onIsSyntheticOblique() const;
434
435 virtual void onGetFontDescriptor(SkFontDescriptor*, bool* isLocal) const = 0;
436
437 virtual void onCharsToGlyphs(SkSpan<const SkUnichar>, SkSpan<SkGlyphID>) const = 0;
438 virtual int onCountGlyphs() const = 0;
439
440 virtual int onGetUPEM() const = 0;
441 virtual bool onGetKerningPairAdjustments(SkSpan<const SkGlyphID>,
442 SkSpan<int32_t> adjustments) const;
443
444 /** Returns the family name of the typeface as known by its font manager.
445 * This name may or may not be produced by the family name iterator.
446 */
447 virtual void onGetFamilyName(SkString* familyName) const = 0;
448 virtual bool onGetPostScriptName(SkString*) const = 0;
449 virtual int onGetResourceName(SkString* resourceName) const; // TODO: = 0;
450
451 /** Returns an iterator over the family names in the font. */
452 virtual LocalizedStrings* onCreateFamilyNameIterator() const = 0;
453
454 virtual int onGetTableTags(SkSpan<SkFontTableTag>) const = 0;
455 virtual size_t onGetTableData(SkFontTableTag, size_t offset,
456 size_t length, void* data) const = 0;
457 virtual sk_sp<SkData> onCopyTableData(SkFontTableTag) const;
458
459 virtual bool onComputeBounds(SkRect*) const;
460
461 virtual void* onGetCTFontRef() const { return nullptr; }
462
463 private:
464 /** Returns true if the typeface's glyph masks may refer to the foreground
465 * paint foreground color. This is needed to determine caching requirements. Usually true for
466 * typefaces that contain a COLR table.
467 */
468 bool glyphMaskNeedsCurrentColor() const;
469 friend class SkStrikeServerImpl; // glyphMaskNeedsCurrentColor
470 friend class SkTypefaceProxyPrototype; // glyphMaskNeedsCurrentColor
471
472 /** Retrieve detailed typeface metrics. Used by the PDF backend. */
473 std::unique_ptr<SkAdvancedTypefaceMetrics> getAdvancedMetrics() const;
474 friend class SkRandomTypeface; // getAdvancedMetrics
475 friend class SkPDFFont; // getAdvancedMetrics
476 friend class SkTypeface_proxy;
477 friend class SkFontPriv; // getGlyphToUnicodeMap
478 friend void TestSkTypefaceGlyphToUnicodeMap(SkTypeface&, SkSpan<SkUnichar>);
479
480 private:
481 SkTypefaceID fUniqueID;
482 SkFontStyle fStyle;
483 mutable SkRect fBounds;
484 mutable SkOnce fBoundsOnce;
485 bool fIsFixedPitch;
486
487 using INHERITED = SkWeakRefCnt;
488 };
489 #endif