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