1 /*
2 * Copyright 2011 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 #include "include/core/SkFontMetrics.h"
9 #include "include/core/SkFontMgr.h"
10 #include "include/core/SkStream.h"
11 #include "include/core/SkTypeface.h"
12 #include "include/private/SkMutex.h"
13 #include "include/private/SkOnce.h"
14 #include "include/utils/SkCustomTypeface.h"
15 #include "src/core/SkAdvancedTypefaceMetrics.h"
16 #include "src/core/SkEndian.h"
17 #include "src/core/SkFontDescriptor.h"
18 #include "src/core/SkFontPriv.h"
19 #include "src/core/SkScalerContext.h"
20 #include "src/core/SkSurfacePriv.h"
21 #include "src/core/SkTypefaceCache.h"
22 #include "src/sfnt/SkOTTable_OS_2.h"
23 #include "src/utils/SkUTF.h"
24
SkTypeface(const SkFontStyle & style,bool isFixedPitch)25 SkTypeface::SkTypeface(const SkFontStyle& style, bool isFixedPitch)
26 : fUniqueID(SkTypefaceCache::NewFontID()), fStyle(style), fIsFixedPitch(isFixedPitch) { }
27
~SkTypeface()28 SkTypeface::~SkTypeface() { }
29
30 ///////////////////////////////////////////////////////////////////////////////
31
32 namespace {
33
34 class SkEmptyTypeface : public SkTypeface {
35 public:
Make()36 static sk_sp<SkTypeface> Make() { return sk_sp<SkTypeface>(new SkEmptyTypeface); }
37 protected:
SkEmptyTypeface()38 SkEmptyTypeface() : SkTypeface(SkFontStyle(), true) { }
39
onOpenStream(int * ttcIndex) const40 std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const override { return nullptr; }
onMakeClone(const SkFontArguments & args) const41 sk_sp<SkTypeface> onMakeClone(const SkFontArguments& args) const override {
42 return sk_ref_sp(this);
43 }
onCreateScalerContext(const SkScalerContextEffects & effects,const SkDescriptor * desc) const44 std::unique_ptr<SkScalerContext> onCreateScalerContext(
45 const SkScalerContextEffects& effects, const SkDescriptor* desc) const override
46 {
47 return SkScalerContext::MakeEmpty(
48 sk_ref_sp(const_cast<SkEmptyTypeface*>(this)), effects, desc);
49 }
onFilterRec(SkScalerContextRec *) const50 void onFilterRec(SkScalerContextRec*) const override { }
onGetAdvancedMetrics() const51 std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const override {
52 return nullptr;
53 }
onGetFontDescriptor(SkFontDescriptor *,bool *) const54 void onGetFontDescriptor(SkFontDescriptor*, bool*) const override { }
onCharsToGlyphs(const SkUnichar * chars,int count,SkGlyphID glyphs[]) const55 void onCharsToGlyphs(const SkUnichar* chars, int count, SkGlyphID glyphs[]) const override {
56 sk_bzero(glyphs, count * sizeof(glyphs[0]));
57 }
onCountGlyphs() const58 int onCountGlyphs() const override { return 0; }
getPostScriptGlyphNames(SkString *) const59 void getPostScriptGlyphNames(SkString*) const override {}
getGlyphToUnicodeMap(SkUnichar *) const60 void getGlyphToUnicodeMap(SkUnichar*) const override {}
onGetUPEM() const61 int onGetUPEM() const override { return 0; }
62 class EmptyLocalizedStrings : public SkTypeface::LocalizedStrings {
63 public:
next(SkTypeface::LocalizedString *)64 bool next(SkTypeface::LocalizedString*) override { return false; }
65 };
onGetFamilyName(SkString * familyName) const66 void onGetFamilyName(SkString* familyName) const override {
67 familyName->reset();
68 }
onGetPostScriptName(SkString *) const69 bool onGetPostScriptName(SkString*) const override {
70 return false;
71 }
onCreateFamilyNameIterator() const72 SkTypeface::LocalizedStrings* onCreateFamilyNameIterator() const override {
73 return new EmptyLocalizedStrings;
74 }
onGlyphMaskNeedsCurrentColor() const75 bool onGlyphMaskNeedsCurrentColor() const override {
76 return false;
77 }
onGetVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],int coordinateCount) const78 int onGetVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],
79 int coordinateCount) const override
80 {
81 return 0;
82 }
onGetVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],int parameterCount) const83 int onGetVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],
84 int parameterCount) const override
85 {
86 return 0;
87 }
onGetTableTags(SkFontTableTag tags[]) const88 int onGetTableTags(SkFontTableTag tags[]) const override { return 0; }
onGetTableData(SkFontTableTag,size_t,size_t,void *) const89 size_t onGetTableData(SkFontTableTag, size_t, size_t, void*) const override {
90 return 0;
91 }
92 };
93
94 } // namespace
95
FromOldStyle(Style oldStyle)96 SkFontStyle SkTypeface::FromOldStyle(Style oldStyle) {
97 return SkFontStyle((oldStyle & SkTypeface::kBold) ? SkFontStyle::kBold_Weight
98 : SkFontStyle::kNormal_Weight,
99 SkFontStyle::kNormal_Width,
100 (oldStyle & SkTypeface::kItalic) ? SkFontStyle::kItalic_Slant
101 : SkFontStyle::kUpright_Slant);
102 }
103
GetDefaultTypeface(Style style)104 SkTypeface* SkTypeface::GetDefaultTypeface(Style style) {
105 static SkOnce once[4];
106 static sk_sp<SkTypeface> defaults[4];
107
108 SkASSERT((int)style < 4);
109 once[style]([style] {
110 sk_sp<SkFontMgr> fm(SkFontMgr::RefDefault());
111 auto t = fm->legacyMakeTypeface(nullptr, FromOldStyle(style));
112 defaults[style] = t ? t : SkEmptyTypeface::Make();
113 });
114 return defaults[style].get();
115 }
116
MakeDefault()117 sk_sp<SkTypeface> SkTypeface::MakeDefault() {
118 return sk_ref_sp(GetDefaultTypeface());
119 }
120
UniqueID(const SkTypeface * face)121 uint32_t SkTypeface::UniqueID(const SkTypeface* face) {
122 if (nullptr == face) {
123 face = GetDefaultTypeface();
124 }
125 return face->uniqueID();
126 }
127
Equal(const SkTypeface * facea,const SkTypeface * faceb)128 bool SkTypeface::Equal(const SkTypeface* facea, const SkTypeface* faceb) {
129 return facea == faceb || SkTypeface::UniqueID(facea) == SkTypeface::UniqueID(faceb);
130 }
131
132 ///////////////////////////////////////////////////////////////////////////////
133
MakeFromName(const char name[],SkFontStyle fontStyle)134 sk_sp<SkTypeface> SkTypeface::MakeFromName(const char name[],
135 SkFontStyle fontStyle) {
136 if (nullptr == name && (fontStyle.slant() == SkFontStyle::kItalic_Slant ||
137 fontStyle.slant() == SkFontStyle::kUpright_Slant) &&
138 (fontStyle.weight() == SkFontStyle::kBold_Weight ||
139 fontStyle.weight() == SkFontStyle::kNormal_Weight)) {
140 return sk_ref_sp(GetDefaultTypeface(static_cast<SkTypeface::Style>(
141 (fontStyle.slant() == SkFontStyle::kItalic_Slant ? SkTypeface::kItalic :
142 SkTypeface::kNormal) |
143 (fontStyle.weight() == SkFontStyle::kBold_Weight ? SkTypeface::kBold :
144 SkTypeface::kNormal))));
145 }
146 return SkFontMgr::RefDefault()->legacyMakeTypeface(name, fontStyle);
147 }
148
MakeFromStream(std::unique_ptr<SkStreamAsset> stream,int index)149 sk_sp<SkTypeface> SkTypeface::MakeFromStream(std::unique_ptr<SkStreamAsset> stream, int index) {
150 if (!stream) {
151 return nullptr;
152 }
153 return SkFontMgr::RefDefault()->makeFromStream(std::move(stream), index);
154 }
155
MakeFromData(sk_sp<SkData> data,int index)156 sk_sp<SkTypeface> SkTypeface::MakeFromData(sk_sp<SkData> data, int index) {
157 if (!data) {
158 return nullptr;
159 }
160 return SkFontMgr::RefDefault()->makeFromData(std::move(data), index);
161 }
162
MakeFromFile(const char path[],int index)163 sk_sp<SkTypeface> SkTypeface::MakeFromFile(const char path[], int index) {
164 return SkFontMgr::RefDefault()->makeFromFile(path, index);
165 }
166
makeClone(const SkFontArguments & args) const167 sk_sp<SkTypeface> SkTypeface::makeClone(const SkFontArguments& args) const {
168 return this->onMakeClone(args);
169 }
170
171 ///////////////////////////////////////////////////////////////////////////////
172
serialize(SkWStream * wstream,SerializeBehavior behavior) const173 void SkTypeface::serialize(SkWStream* wstream, SerializeBehavior behavior) const {
174 bool isLocalData = false;
175 SkFontDescriptor desc;
176 this->onGetFontDescriptor(&desc, &isLocalData);
177
178 bool shouldSerializeData = false;
179 switch (behavior) {
180 case SerializeBehavior::kDoIncludeData: shouldSerializeData = true; break;
181 case SerializeBehavior::kDontIncludeData: shouldSerializeData = false; break;
182 case SerializeBehavior::kIncludeDataIfLocal: shouldSerializeData = isLocalData; break;
183 }
184
185 if (shouldSerializeData) {
186 int index;
187 desc.setStream(this->openStream(&index));
188 if (desc.hasStream()) {
189 desc.setCollectionIndex(index);
190 }
191
192 int numAxes = this->getVariationDesignPosition(nullptr, 0);
193 if (0 < numAxes) {
194 numAxes = this->getVariationDesignPosition(desc.setVariationCoordinates(numAxes), numAxes);
195 if (numAxes <= 0) {
196 desc.setVariationCoordinates(0);
197 }
198 }
199 }
200 desc.serialize(wstream);
201 }
202
serialize(SerializeBehavior behavior) const203 sk_sp<SkData> SkTypeface::serialize(SerializeBehavior behavior) const {
204 SkDynamicMemoryWStream stream;
205 this->serialize(&stream, behavior);
206 return stream.detachAsData();
207 }
208
MakeDeserialize(SkStream * stream)209 sk_sp<SkTypeface> SkTypeface::MakeDeserialize(SkStream* stream) {
210 SkFontDescriptor desc;
211 if (!SkFontDescriptor::Deserialize(stream, &desc)) {
212 return nullptr;
213 }
214
215 if (desc.hasStream()) {
216 if (auto tf = SkCustomTypefaceBuilder::Deserialize(desc.dupStream().get())) {
217 return tf;
218 }
219 }
220
221 if (desc.hasStream()) {
222 SkFontArguments args;
223 args.setCollectionIndex(desc.getCollectionIndex());
224 args.setVariationDesignPosition({desc.getVariation(), desc.getVariationCoordinateCount()});
225 sk_sp<SkFontMgr> defaultFm = SkFontMgr::RefDefault();
226 sk_sp<SkTypeface> typeface = defaultFm->makeFromStream(desc.detachStream(), args);
227 if (typeface) {
228 return typeface;
229 }
230 }
231
232 return SkTypeface::MakeFromName(desc.getFamilyName(), desc.getStyle());
233 }
234
235 ///////////////////////////////////////////////////////////////////////////////
236
glyphMaskNeedsCurrentColor() const237 bool SkTypeface::glyphMaskNeedsCurrentColor() const {
238 return this->onGlyphMaskNeedsCurrentColor();
239 }
240
getVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],int coordinateCount) const241 int SkTypeface::getVariationDesignPosition(
242 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
243 {
244 return this->onGetVariationDesignPosition(coordinates, coordinateCount);
245 }
246
getVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],int parameterCount) const247 int SkTypeface::getVariationDesignParameters(
248 SkFontParameters::Variation::Axis parameters[], int parameterCount) const
249 {
250 return this->onGetVariationDesignParameters(parameters, parameterCount);
251 }
252
countTables() const253 int SkTypeface::countTables() const {
254 return this->onGetTableTags(nullptr);
255 }
256
getTableTags(SkFontTableTag tags[]) const257 int SkTypeface::getTableTags(SkFontTableTag tags[]) const {
258 return this->onGetTableTags(tags);
259 }
260
getTableSize(SkFontTableTag tag) const261 size_t SkTypeface::getTableSize(SkFontTableTag tag) const {
262 return this->onGetTableData(tag, 0, ~0U, nullptr);
263 }
264
getTableData(SkFontTableTag tag,size_t offset,size_t length,void * data) const265 size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length,
266 void* data) const {
267 return this->onGetTableData(tag, offset, length, data);
268 }
269
copyTableData(SkFontTableTag tag) const270 sk_sp<SkData> SkTypeface::copyTableData(SkFontTableTag tag) const {
271 return this->onCopyTableData(tag);
272 }
273
onCopyTableData(SkFontTableTag tag) const274 sk_sp<SkData> SkTypeface::onCopyTableData(SkFontTableTag tag) const {
275 size_t size = this->getTableSize(tag);
276 if (size) {
277 sk_sp<SkData> data = SkData::MakeUninitialized(size);
278 (void)this->getTableData(tag, 0, size, data->writable_data());
279 return data;
280 }
281 return nullptr;
282 }
283
openStream(int * ttcIndex) const284 std::unique_ptr<SkStreamAsset> SkTypeface::openStream(int* ttcIndex) const {
285 int ttcIndexStorage;
286 if (nullptr == ttcIndex) {
287 // So our subclasses don't need to check for null param
288 ttcIndex = &ttcIndexStorage;
289 }
290 return this->onOpenStream(ttcIndex);
291 }
292
createScalerContext(const SkScalerContextEffects & effects,const SkDescriptor * desc) const293 std::unique_ptr<SkScalerContext> SkTypeface::createScalerContext(
294 const SkScalerContextEffects& effects, const SkDescriptor* desc) const {
295 std::unique_ptr<SkScalerContext> scalerContext = this->onCreateScalerContext(effects, desc);
296 SkASSERT(scalerContext);
297 return scalerContext;
298 }
299
unicharsToGlyphs(const SkUnichar uni[],int count,SkGlyphID glyphs[]) const300 void SkTypeface::unicharsToGlyphs(const SkUnichar uni[], int count, SkGlyphID glyphs[]) const {
301 if (count > 0 && glyphs && uni) {
302 this->onCharsToGlyphs(uni, count, glyphs);
303 }
304 }
305
unicharToGlyph(SkUnichar uni) const306 SkGlyphID SkTypeface::unicharToGlyph(SkUnichar uni) const {
307 SkGlyphID glyphs[1] = { 0 };
308 this->onCharsToGlyphs(&uni, 1, glyphs);
309 return glyphs[0];
310 }
311
312 namespace {
313 class SkConvertToUTF32 {
314 public:
SkConvertToUTF32()315 SkConvertToUTF32() {}
316
convert(const void * text,size_t byteLength,SkTextEncoding encoding)317 const SkUnichar* convert(const void* text, size_t byteLength, SkTextEncoding encoding) {
318 const SkUnichar* uni;
319 switch (encoding) {
320 case SkTextEncoding::kUTF8: {
321 uni = fStorage.reset(byteLength);
322 const char* ptr = (const char*)text;
323 const char* end = ptr + byteLength;
324 for (int i = 0; ptr < end; ++i) {
325 fStorage[i] = SkUTF::NextUTF8(&ptr, end);
326 }
327 } break;
328 case SkTextEncoding::kUTF16: {
329 uni = fStorage.reset(byteLength);
330 const uint16_t* ptr = (const uint16_t*)text;
331 const uint16_t* end = ptr + (byteLength >> 1);
332 for (int i = 0; ptr < end; ++i) {
333 fStorage[i] = SkUTF::NextUTF16(&ptr, end);
334 }
335 } break;
336 case SkTextEncoding::kUTF32:
337 uni = (const SkUnichar*)text;
338 break;
339 default:
340 SK_ABORT("unexpected enum");
341 }
342 return uni;
343 }
344
345 private:
346 SkAutoSTMalloc<256, SkUnichar> fStorage;
347 };
348 }
349
textToGlyphs(const void * text,size_t byteLength,SkTextEncoding encoding,SkGlyphID glyphs[],int maxGlyphCount) const350 int SkTypeface::textToGlyphs(const void* text, size_t byteLength, SkTextEncoding encoding,
351 SkGlyphID glyphs[], int maxGlyphCount) const {
352 if (0 == byteLength) {
353 return 0;
354 }
355
356 SkASSERT(text);
357
358 int count = SkFontPriv::CountTextElements(text, byteLength, encoding);
359 if (!glyphs || count > maxGlyphCount) {
360 return count;
361 }
362
363 if (encoding == SkTextEncoding::kGlyphID) {
364 memcpy(glyphs, text, count << 1);
365 return count;
366 }
367
368 SkConvertToUTF32 storage;
369 const SkUnichar* uni = storage.convert(text, byteLength, encoding);
370
371 this->unicharsToGlyphs(uni, count, glyphs);
372 return count;
373 }
374
countGlyphs() const375 int SkTypeface::countGlyphs() const {
376 return this->onCountGlyphs();
377 }
378
getUnitsPerEm() const379 int SkTypeface::getUnitsPerEm() const {
380 // should we try to cache this in the base-class?
381 return this->onGetUPEM();
382 }
383
getKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const384 bool SkTypeface::getKerningPairAdjustments(const uint16_t glyphs[], int count,
385 int32_t adjustments[]) const {
386 SkASSERT(count >= 0);
387 // check for the only legal way to pass a nullptr.. everything is 0
388 // in which case they just want to know if this face can possibly support
389 // kerning (true) or never (false).
390 if (nullptr == glyphs || nullptr == adjustments) {
391 SkASSERT(nullptr == glyphs);
392 SkASSERT(0 == count);
393 SkASSERT(nullptr == adjustments);
394 }
395 return this->onGetKerningPairAdjustments(glyphs, count, adjustments);
396 }
397
createFamilyNameIterator() const398 SkTypeface::LocalizedStrings* SkTypeface::createFamilyNameIterator() const {
399 return this->onCreateFamilyNameIterator();
400 }
401
getFamilyName(SkString * name) const402 void SkTypeface::getFamilyName(SkString* name) const {
403 SkASSERT(name);
404 this->onGetFamilyName(name);
405 }
406
getPostScriptName(SkString * name) const407 bool SkTypeface::getPostScriptName(SkString* name) const {
408 return this->onGetPostScriptName(name);
409 }
410
getGlyphToUnicodeMap(SkUnichar * dst) const411 void SkTypeface::getGlyphToUnicodeMap(SkUnichar* dst) const {
412 sk_bzero(dst, sizeof(SkUnichar) * this->countGlyphs());
413 }
414
getAdvancedMetrics() const415 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface::getAdvancedMetrics() const {
416 std::unique_ptr<SkAdvancedTypefaceMetrics> result = this->onGetAdvancedMetrics();
417 if (result && result->fPostScriptName.isEmpty()) {
418 result->fPostScriptName = result->fFontName;
419 }
420 if (result && result->fType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
421 SkOTTableOS2::Version::V2::Type::Field fsType;
422 constexpr SkFontTableTag os2Tag = SkTEndian_SwapBE32(SkOTTableOS2::TAG);
423 constexpr size_t fsTypeOffset = offsetof(SkOTTableOS2::Version::V2, fsType);
424 if (this->getTableData(os2Tag, fsTypeOffset, sizeof(fsType), &fsType) == sizeof(fsType)) {
425 if (fsType.Bitmap || (fsType.Restricted && !(fsType.PreviewPrint || fsType.Editable))) {
426 result->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
427 }
428 if (fsType.NoSubsetting) {
429 result->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
430 }
431 }
432 }
433 return result;
434 }
435
onGetKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const436 bool SkTypeface::onGetKerningPairAdjustments(const uint16_t glyphs[], int count,
437 int32_t adjustments[]) const {
438 return false;
439 }
440
441 ///////////////////////////////////////////////////////////////////////////////
442
443 #include "include/core/SkPaint.h"
444 #include "src/core/SkDescriptor.h"
445
getBounds() const446 SkRect SkTypeface::getBounds() const {
447 fBoundsOnce([this] {
448 if (!this->onComputeBounds(&fBounds)) {
449 fBounds.setEmpty();
450 }
451 });
452 return fBounds;
453 }
454
onComputeBounds(SkRect * bounds) const455 bool SkTypeface::onComputeBounds(SkRect* bounds) const {
456 // we use a big size to ensure lots of significant bits from the scalercontext.
457 // then we scale back down to return our final answer (at 1-pt)
458 const SkScalar textSize = 2048;
459 const SkScalar invTextSize = 1 / textSize;
460
461 SkFont font;
462 font.setTypeface(sk_ref_sp(const_cast<SkTypeface*>(this)));
463 font.setSize(textSize);
464 font.setLinearMetrics(true);
465
466 SkScalerContextRec rec;
467 SkScalerContextEffects effects;
468
469 SkScalerContext::MakeRecAndEffectsFromFont(font, &rec, &effects);
470
471 SkAutoDescriptor ad;
472 SkScalerContextEffects noeffects;
473 SkScalerContext::AutoDescriptorGivenRecAndEffects(rec, noeffects, &ad);
474
475 std::unique_ptr<SkScalerContext> ctx = this->createScalerContext(noeffects, ad.getDesc());
476
477 SkFontMetrics fm;
478 ctx->getFontMetrics(&fm);
479 if (!fm.hasBounds()) {
480 return false;
481 }
482 bounds->setLTRB(fm.fXMin * invTextSize, fm.fTop * invTextSize,
483 fm.fXMax * invTextSize, fm.fBottom * invTextSize);
484 return true;
485 }
486
onGetAdvancedMetrics() const487 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface::onGetAdvancedMetrics() const {
488 SkDEBUGFAIL("Typefaces that need to work with PDF backend must override this.");
489 return nullptr;
490 }
491