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 using SkTypefaceID = uint32_t; 33 34 // SkFontID is deprecated, please use SkTypefaceID. 35 using SkFontID = SkTypefaceID; 36 37 38 /** Machine endian. */ 39 typedef uint32_t SkFontTableTag; 40 41 /** \class SkTypeface 42 43 The SkTypeface class specifies the typeface and intrinsic style of a font. 44 This is used in the paint, along with optionally algorithmic settings like 45 textSize, textSkewX, textScaleX, kFakeBoldText_Mask, to specify 46 how text appears when drawn (and measured). 47 48 Typeface objects are immutable, and so they can be shared between threads. 49 */ 50 class SK_API SkTypeface : public SkWeakRefCnt { 51 public: 52 /** Returns the typeface's intrinsic style attributes. */ fontStyle()53 SkFontStyle fontStyle() const { 54 return fStyle; 55 } 56 57 /** Returns true if style() has the kBold bit set. */ isBold()58 bool isBold() const { return fStyle.weight() >= SkFontStyle::kSemiBold_Weight; } 59 60 /** Returns true if style() has the kItalic bit set. */ isItalic()61 bool isItalic() const { return fStyle.slant() != SkFontStyle::kUpright_Slant; } 62 63 /** Returns true if the typeface claims to be fixed-pitch. 64 * This is a style bit, advance widths may vary even if this returns true. 65 */ isFixedPitch()66 bool isFixedPitch() const { return fIsFixedPitch; } 67 68 /** Copy into 'coordinates' (allocated by the caller) the design variation coordinates. 69 * 70 * @param coordinates the buffer into which to write the design variation coordinates. 71 * @param coordinateCount the number of entries available through 'coordinates'. 72 * 73 * @return The number of axes, or -1 if there is an error. 74 * If 'coordinates != nullptr' and 'coordinateCount >= numAxes' then 'coordinates' will be 75 * filled with the variation coordinates describing the position of this typeface in design 76 * variation space. It is possible the number of axes can be retrieved but actual position 77 * cannot. 78 */ 79 int getVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[], 80 int coordinateCount) const; 81 82 /** Copy into 'parameters' (allocated by the caller) the design variation parameters. 83 * 84 * @param parameters the buffer into which to write the design variation parameters. 85 * @param coordinateCount the number of entries available through 'parameters'. 86 * 87 * @return The number of axes, or -1 if there is an error. 88 * If 'parameters != nullptr' and 'parameterCount >= 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(SkFontParameters::Variation::Axis parameters[], 94 int parameterCount) const; 95 96 /** Return a 32bit value for this typeface, unique for the underlying font 97 data. Will never return 0. 98 */ uniqueID()99 SkTypefaceID uniqueID() const { return fUniqueID; } 100 101 /** Return the uniqueID for the specified typeface. If the face is null, 102 resolve it to the default font and return its uniqueID. Will never 103 return 0. 104 */ 105 static SkTypefaceID UniqueID(const SkTypeface* face); 106 107 /** Returns true if the two typefaces reference the same underlying font, 108 handling either being null (treating null as the default font) 109 */ 110 static bool Equal(const SkTypeface* facea, const SkTypeface* faceb); 111 112 /** Returns the default normal typeface, which is never nullptr. */ 113 static sk_sp<SkTypeface> MakeDefault(); 114 115 /** Creates a new reference to the typeface that most closely matches the 116 requested familyName and fontStyle. This method allows extended font 117 face specifiers as in the SkFontStyle type. Will never return null. 118 119 @param familyName May be NULL. The name of the font family. 120 @param fontStyle The style of the typeface. 121 @return reference to the closest-matching typeface. Call must call 122 unref() when they are done. 123 */ 124 static sk_sp<SkTypeface> MakeFromName(const char familyName[], SkFontStyle fontStyle); 125 126 /** Return a new typeface given a file. If the file does not exist, or is 127 not a valid font file, returns nullptr. 128 */ 129 static sk_sp<SkTypeface> MakeFromFile(const char path[], int index = 0); 130 131 /** Return a new typeface given a stream. If the stream is 132 not a valid font file, returns nullptr. Ownership of the stream is 133 transferred, so the caller must not reference it again. 134 */ 135 static sk_sp<SkTypeface> MakeFromStream(std::unique_ptr<SkStreamAsset> stream, int index = 0); 136 137 /** Return a new typeface given a SkData. If the data is null, or is not a valid font file, 138 * returns nullptr. 139 */ 140 static sk_sp<SkTypeface> MakeFromData(sk_sp<SkData>, int index = 0); 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 /** 180 * Given an array of UTF32 character codes, return their corresponding glyph IDs. 181 * 182 * @param chars pointer to the array of UTF32 chars 183 * @param number of chars and glyphs 184 * @param glyphs returns the corresponding glyph IDs for each character. 185 */ 186 void unicharsToGlyphs(const SkUnichar uni[], int count, SkGlyphID glyphs[]) const; 187 188 int textToGlyphs(const void* text, size_t byteLength, SkTextEncoding encoding, 189 SkGlyphID glyphs[], int maxGlyphCount) const; 190 191 /** 192 * Return the glyphID that corresponds to the specified unicode code-point 193 * (in UTF32 encoding). If the unichar is not supported, returns 0. 194 * 195 * This is a short-cut for calling unicharsToGlyphs(). 196 */ 197 SkGlyphID unicharToGlyph(SkUnichar unichar) const; 198 199 /** 200 * Return the number of glyphs in the typeface. 201 */ 202 int countGlyphs() const; 203 204 // Table getters -- may fail if the underlying font format is not organized 205 // as 4-byte tables. 206 207 /** Return the number of tables in the font. */ 208 int countTables() const; 209 210 /** Copy into tags[] (allocated by the caller) the list of table tags in 211 * the font, and return the number. This will be the same as CountTables() 212 * or 0 if an error occured. If tags == NULL, this only returns the count 213 * (the same as calling countTables()). 214 */ 215 int getTableTags(SkFontTableTag tags[]) const; 216 217 /** Given a table tag, return the size of its contents, or 0 if not present 218 */ 219 size_t getTableSize(SkFontTableTag) const; 220 221 /** Copy the contents of a table into data (allocated by the caller). Note 222 * that the contents of the table will be in their native endian order 223 * (which for most truetype tables is big endian). If the table tag is 224 * not found, or there is an error copying the data, then 0 is returned. 225 * If this happens, it is possible that some or all of the memory pointed 226 * to by data may have been written to, even though an error has occured. 227 * 228 * @param tag The table tag whose contents are to be copied 229 * @param offset The offset in bytes into the table's contents where the 230 * copy should start from. 231 * @param length The number of bytes, starting at offset, of table data 232 * to copy. 233 * @param data storage address where the table contents are copied to 234 * @return the number of bytes actually copied into data. If offset+length 235 * exceeds the table's size, then only the bytes up to the table's 236 * size are actually copied, and this is the value returned. If 237 * offset > the table's size, or tag is not a valid table, 238 * then 0 is returned. 239 */ 240 size_t getTableData(SkFontTableTag tag, size_t offset, size_t length, 241 void* data) const; 242 243 /** 244 * Return an immutable copy of the requested font table, or nullptr if that table was 245 * not found. This can sometimes be faster than calling getTableData() twice: once to find 246 * the length, and then again to copy the data. 247 * 248 * @param tag The table tag whose contents are to be copied 249 * @return an immutable copy of the table's data, or nullptr. 250 */ 251 sk_sp<SkData> copyTableData(SkFontTableTag tag) const; 252 253 /** 254 * Return the units-per-em value for this typeface, or zero if there is an 255 * error. 256 */ 257 int getUnitsPerEm() const; 258 259 /** 260 * Given a run of glyphs, return the associated horizontal adjustments. 261 * Adjustments are in "design units", which are integers relative to the 262 * typeface's units per em (see getUnitsPerEm). 263 * 264 * Some typefaces are known to never support kerning. Calling this method 265 * with all zeros (e.g. getKerningPairAdustments(NULL, 0, NULL)) returns 266 * a boolean indicating if the typeface might support kerning. If it 267 * returns false, then it will always return false (no kerning) for all 268 * possible glyph runs. If it returns true, then it *may* return true for 269 * somne glyph runs. 270 * 271 * If count is non-zero, then the glyphs parameter must point to at least 272 * [count] valid glyph IDs, and the adjustments parameter must be 273 * sized to at least [count - 1] entries. If the method returns true, then 274 * [count-1] entries in the adjustments array will be set. If the method 275 * returns false, then no kerning should be applied, and the adjustments 276 * array will be in an undefined state (possibly some values may have been 277 * written, but none of them should be interpreted as valid values). 278 */ 279 bool getKerningPairAdjustments(const SkGlyphID glyphs[], int count, 280 int32_t adjustments[]) const; 281 282 struct LocalizedString { 283 SkString fString; 284 SkString fLanguage; 285 }; 286 class LocalizedStrings { 287 public: 288 LocalizedStrings() = default; ~LocalizedStrings()289 virtual ~LocalizedStrings() { } 290 virtual bool next(LocalizedString* localizedString) = 0; unref()291 void unref() { delete this; } 292 293 private: 294 LocalizedStrings(const LocalizedStrings&) = delete; 295 LocalizedStrings& operator=(const LocalizedStrings&) = delete; 296 }; 297 /** 298 * Returns an iterator which will attempt to enumerate all of the 299 * family names specified by the font. 300 * It is the caller's responsibility to unref() the returned pointer. 301 */ 302 LocalizedStrings* createFamilyNameIterator() const; 303 304 /** 305 * Return the family name for this typeface. It will always be returned 306 * encoded as UTF8, but the language of the name is whatever the host 307 * platform chooses. 308 */ 309 void getFamilyName(SkString* name) const; 310 311 /** 312 * Return the PostScript name for this typeface. 313 * Value may change based on variation parameters. 314 * Returns false if no PostScript name is available. 315 */ 316 bool getPostScriptName(SkString* name) const; 317 318 /** 319 * Return a stream for the contents of the font data, or NULL on failure. 320 * If ttcIndex is not null, it is set to the TrueTypeCollection index 321 * of this typeface within the stream, or 0 if the stream is not a 322 * collection. 323 * The caller is responsible for deleting the stream. 324 */ 325 std::unique_ptr<SkStreamAsset> openStream(int* ttcIndex) const; 326 327 /** 328 * Return a stream for the contents of the font data. 329 * Returns nullptr on failure or if the font data isn't already available in stream form. 330 * Use when the stream can be used opportunistically but the calling code would prefer 331 * to fall back to table access if creating the stream would be expensive. 332 * Otherwise acts the same as openStream. 333 */ 334 std::unique_ptr<SkStreamAsset> openExistingStream(int* ttcIndex) const; 335 336 /** 337 * Return a scalercontext for the given descriptor. It may return a 338 * stub scalercontext that will not crash, but will draw nothing. 339 */ 340 std::unique_ptr<SkScalerContext> createScalerContext(const SkScalerContextEffects&, 341 const SkDescriptor*) const; 342 343 /** 344 * Return a rectangle (scaled to 1-pt) that represents the union of the bounds of all 345 * of the glyphs, but each one positioned at (0,). This may be conservatively large, and 346 * will not take into account any hinting or other size-specific adjustments. 347 */ 348 SkRect getBounds() const; 349 350 // PRIVATE / EXPERIMENTAL -- do not call filterRec(SkScalerContextRec * rec)351 void filterRec(SkScalerContextRec* rec) const { 352 this->onFilterRec(rec); 353 } 354 // PRIVATE / EXPERIMENTAL -- do not call getFontDescriptor(SkFontDescriptor * desc,bool * isLocal)355 void getFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const { 356 this->onGetFontDescriptor(desc, isLocal); 357 } 358 // PRIVATE / EXPERIMENTAL -- do not call internal_private_getCTFontRef()359 void* internal_private_getCTFontRef() const { 360 return this->onGetCTFontRef(); 361 } 362 363 protected: 364 explicit SkTypeface(const SkFontStyle& style, bool isFixedPitch = false); 365 ~SkTypeface() override; 366 367 virtual sk_sp<SkTypeface> onMakeClone(const SkFontArguments&) const = 0; 368 369 /** Sets the fixedPitch bit. If used, must be called in the constructor. */ setIsFixedPitch(bool isFixedPitch)370 void setIsFixedPitch(bool isFixedPitch) { fIsFixedPitch = isFixedPitch; } 371 /** Sets the font style. If used, must be called in the constructor. */ setFontStyle(SkFontStyle style)372 void setFontStyle(SkFontStyle style) { fStyle = style; } 373 374 // Must return a valid scaler context. It can not return nullptr. 375 virtual std::unique_ptr<SkScalerContext> onCreateScalerContext(const SkScalerContextEffects&, 376 const SkDescriptor*) const = 0; 377 virtual void onFilterRec(SkScalerContextRec*) const = 0; 378 friend class SkScalerContext; // onFilterRec 379 380 // Subclasses *must* override this method to work with the PDF backend. 381 virtual std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const = 0; 382 // For type1 postscript fonts only, set the glyph names for each glyph. 383 // destination array is non-null, and points to an array of size this->countGlyphs(). 384 // Backends that do not suport type1 fonts should not override. 385 virtual void getPostScriptGlyphNames(SkString*) const = 0; 386 387 // The mapping from glyph to Unicode; array indices are glyph ids. 388 // For each glyph, give the default Unicode value, if it exists. 389 // dstArray is non-null, and points to an array of size this->countGlyphs(). 390 virtual void getGlyphToUnicodeMap(SkUnichar* dstArray) const = 0; 391 392 virtual std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const = 0; 393 394 virtual std::unique_ptr<SkStreamAsset> onOpenExistingStream(int* ttcIndex) const; 395 396 virtual bool onGlyphMaskNeedsCurrentColor() const = 0; 397 398 virtual int onGetVariationDesignPosition( 399 SkFontArguments::VariationPosition::Coordinate coordinates[], 400 int coordinateCount) const = 0; 401 402 virtual int onGetVariationDesignParameters( 403 SkFontParameters::Variation::Axis parameters[], int parameterCount) const = 0; 404 405 virtual void onGetFontDescriptor(SkFontDescriptor*, bool* isLocal) const = 0; 406 407 virtual void onCharsToGlyphs(const SkUnichar* chars, int count, SkGlyphID glyphs[]) const = 0; 408 virtual int onCountGlyphs() const = 0; 409 410 virtual int onGetUPEM() const = 0; 411 virtual bool onGetKerningPairAdjustments(const SkGlyphID glyphs[], int count, 412 int32_t adjustments[]) const; 413 414 /** Returns the family name of the typeface as known by its font manager. 415 * This name may or may not be produced by the family name iterator. 416 */ 417 virtual void onGetFamilyName(SkString* familyName) const = 0; 418 virtual bool onGetPostScriptName(SkString*) const = 0; 419 420 /** Returns an iterator over the family names in the font. */ 421 virtual LocalizedStrings* onCreateFamilyNameIterator() const = 0; 422 423 virtual int onGetTableTags(SkFontTableTag tags[]) const = 0; 424 virtual size_t onGetTableData(SkFontTableTag, size_t offset, 425 size_t length, void* data) const = 0; 426 virtual sk_sp<SkData> onCopyTableData(SkFontTableTag) const; 427 428 virtual bool onComputeBounds(SkRect*) const; 429 onGetCTFontRef()430 virtual void* onGetCTFontRef() const { return nullptr; } 431 432 private: 433 /** Returns true if the typeface's glyph masks may refer to the foreground 434 * paint foreground color. This is needed to determine caching requirements. Usually true for 435 * typefaces that contain a COLR table. 436 */ 437 bool glyphMaskNeedsCurrentColor() const; 438 friend class SkStrikeServerImpl; // 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 445 /** Style specifies the intrinsic style attributes of a given typeface */ 446 enum Style { 447 kNormal = 0, 448 kBold = 0x01, 449 kItalic = 0x02, 450 451 // helpers 452 kBoldItalic = 0x03 453 }; 454 static SkFontStyle FromOldStyle(Style oldStyle); 455 static SkTypeface* GetDefaultTypeface(Style style = SkTypeface::kNormal); 456 457 friend class SkFontPriv; // GetDefaultTypeface 458 friend class SkPaintPriv; // GetDefaultTypeface 459 friend class SkFont; // getGlyphToUnicodeMap 460 461 private: 462 SkTypefaceID fUniqueID; 463 SkFontStyle fStyle; 464 mutable SkRect fBounds; 465 mutable SkOnce fBoundsOnce; 466 bool fIsFixedPitch; 467 468 using INHERITED = SkWeakRefCnt; 469 }; 470 #endif 471