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
openExistingStream(int * ttcIndex) const235 std::unique_ptr<SkStreamAsset> SkTypeface::openExistingStream(int* ttcIndex) const {
236 int ttcIndexStorage;
237 if (nullptr == ttcIndex) {
238 // So our subclasses don't need to check for null param
239 ttcIndex = &ttcIndexStorage;
240 }
241 return this->onOpenExistingStream(ttcIndex);
242 }
243
onOpenExistingStream(int * ttcIndex) const244 std::unique_ptr<SkStreamAsset> SkTypeface::onOpenExistingStream(int* ttcIndex) const {
245 return this->onOpenStream(ttcIndex);
246 }
247
248 ///////////////////////////////////////////////////////////////////////////////
249
glyphMaskNeedsCurrentColor() const250 bool SkTypeface::glyphMaskNeedsCurrentColor() const {
251 return this->onGlyphMaskNeedsCurrentColor();
252 }
253
getVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],int coordinateCount) const254 int SkTypeface::getVariationDesignPosition(
255 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
256 {
257 return this->onGetVariationDesignPosition(coordinates, coordinateCount);
258 }
259
getVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],int parameterCount) const260 int SkTypeface::getVariationDesignParameters(
261 SkFontParameters::Variation::Axis parameters[], int parameterCount) const
262 {
263 return this->onGetVariationDesignParameters(parameters, parameterCount);
264 }
265
countTables() const266 int SkTypeface::countTables() const {
267 return this->onGetTableTags(nullptr);
268 }
269
getTableTags(SkFontTableTag tags[]) const270 int SkTypeface::getTableTags(SkFontTableTag tags[]) const {
271 return this->onGetTableTags(tags);
272 }
273
getTableSize(SkFontTableTag tag) const274 size_t SkTypeface::getTableSize(SkFontTableTag tag) const {
275 return this->onGetTableData(tag, 0, ~0U, nullptr);
276 }
277
getTableData(SkFontTableTag tag,size_t offset,size_t length,void * data) const278 size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length,
279 void* data) const {
280 return this->onGetTableData(tag, offset, length, data);
281 }
282
copyTableData(SkFontTableTag tag) const283 sk_sp<SkData> SkTypeface::copyTableData(SkFontTableTag tag) const {
284 return this->onCopyTableData(tag);
285 }
286
onCopyTableData(SkFontTableTag tag) const287 sk_sp<SkData> SkTypeface::onCopyTableData(SkFontTableTag tag) const {
288 size_t size = this->getTableSize(tag);
289 if (size) {
290 sk_sp<SkData> data = SkData::MakeUninitialized(size);
291 (void)this->getTableData(tag, 0, size, data->writable_data());
292 return data;
293 }
294 return nullptr;
295 }
296
openStream(int * ttcIndex) const297 std::unique_ptr<SkStreamAsset> SkTypeface::openStream(int* ttcIndex) const {
298 int ttcIndexStorage;
299 if (nullptr == ttcIndex) {
300 // So our subclasses don't need to check for null param
301 ttcIndex = &ttcIndexStorage;
302 }
303 return this->onOpenStream(ttcIndex);
304 }
305
createScalerContext(const SkScalerContextEffects & effects,const SkDescriptor * desc) const306 std::unique_ptr<SkScalerContext> SkTypeface::createScalerContext(
307 const SkScalerContextEffects& effects, const SkDescriptor* desc) const {
308 std::unique_ptr<SkScalerContext> scalerContext = this->onCreateScalerContext(effects, desc);
309 SkASSERT(scalerContext);
310 return scalerContext;
311 }
312
unicharsToGlyphs(const SkUnichar uni[],int count,SkGlyphID glyphs[]) const313 void SkTypeface::unicharsToGlyphs(const SkUnichar uni[], int count, SkGlyphID glyphs[]) const {
314 if (count > 0 && glyphs && uni) {
315 this->onCharsToGlyphs(uni, count, glyphs);
316 }
317 }
318
unicharToGlyph(SkUnichar uni) const319 SkGlyphID SkTypeface::unicharToGlyph(SkUnichar uni) const {
320 SkGlyphID glyphs[1] = { 0 };
321 this->onCharsToGlyphs(&uni, 1, glyphs);
322 return glyphs[0];
323 }
324
325 namespace {
326 class SkConvertToUTF32 {
327 public:
SkConvertToUTF32()328 SkConvertToUTF32() {}
329
convert(const void * text,size_t byteLength,SkTextEncoding encoding)330 const SkUnichar* convert(const void* text, size_t byteLength, SkTextEncoding encoding) {
331 const SkUnichar* uni;
332 switch (encoding) {
333 case SkTextEncoding::kUTF8: {
334 uni = fStorage.reset(byteLength);
335 const char* ptr = (const char*)text;
336 const char* end = ptr + byteLength;
337 for (int i = 0; ptr < end; ++i) {
338 fStorage[i] = SkUTF::NextUTF8(&ptr, end);
339 }
340 } break;
341 case SkTextEncoding::kUTF16: {
342 uni = fStorage.reset(byteLength);
343 const uint16_t* ptr = (const uint16_t*)text;
344 const uint16_t* end = ptr + (byteLength >> 1);
345 for (int i = 0; ptr < end; ++i) {
346 fStorage[i] = SkUTF::NextUTF16(&ptr, end);
347 }
348 } break;
349 case SkTextEncoding::kUTF32:
350 uni = (const SkUnichar*)text;
351 break;
352 default:
353 SK_ABORT("unexpected enum");
354 }
355 return uni;
356 }
357
358 private:
359 SkAutoSTMalloc<256, SkUnichar> fStorage;
360 };
361 }
362
textToGlyphs(const void * text,size_t byteLength,SkTextEncoding encoding,SkGlyphID glyphs[],int maxGlyphCount) const363 int SkTypeface::textToGlyphs(const void* text, size_t byteLength, SkTextEncoding encoding,
364 SkGlyphID glyphs[], int maxGlyphCount) const {
365 if (0 == byteLength) {
366 return 0;
367 }
368
369 SkASSERT(text);
370
371 int count = SkFontPriv::CountTextElements(text, byteLength, encoding);
372 if (!glyphs || count > maxGlyphCount) {
373 return count;
374 }
375
376 if (encoding == SkTextEncoding::kGlyphID) {
377 memcpy(glyphs, text, count << 1);
378 return count;
379 }
380
381 SkConvertToUTF32 storage;
382 const SkUnichar* uni = storage.convert(text, byteLength, encoding);
383
384 this->unicharsToGlyphs(uni, count, glyphs);
385 return count;
386 }
387
countGlyphs() const388 int SkTypeface::countGlyphs() const {
389 return this->onCountGlyphs();
390 }
391
getUnitsPerEm() const392 int SkTypeface::getUnitsPerEm() const {
393 // should we try to cache this in the base-class?
394 return this->onGetUPEM();
395 }
396
getKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const397 bool SkTypeface::getKerningPairAdjustments(const uint16_t glyphs[], int count,
398 int32_t adjustments[]) const {
399 SkASSERT(count >= 0);
400 // check for the only legal way to pass a nullptr.. everything is 0
401 // in which case they just want to know if this face can possibly support
402 // kerning (true) or never (false).
403 if (nullptr == glyphs || nullptr == adjustments) {
404 SkASSERT(nullptr == glyphs);
405 SkASSERT(0 == count);
406 SkASSERT(nullptr == adjustments);
407 }
408 return this->onGetKerningPairAdjustments(glyphs, count, adjustments);
409 }
410
createFamilyNameIterator() const411 SkTypeface::LocalizedStrings* SkTypeface::createFamilyNameIterator() const {
412 return this->onCreateFamilyNameIterator();
413 }
414
getFamilyName(SkString * name) const415 void SkTypeface::getFamilyName(SkString* name) const {
416 SkASSERT(name);
417 this->onGetFamilyName(name);
418 }
419
getPostScriptName(SkString * name) const420 bool SkTypeface::getPostScriptName(SkString* name) const {
421 return this->onGetPostScriptName(name);
422 }
423
getGlyphToUnicodeMap(SkUnichar * dst) const424 void SkTypeface::getGlyphToUnicodeMap(SkUnichar* dst) const {
425 sk_bzero(dst, sizeof(SkUnichar) * this->countGlyphs());
426 }
427
getAdvancedMetrics() const428 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface::getAdvancedMetrics() const {
429 std::unique_ptr<SkAdvancedTypefaceMetrics> result = this->onGetAdvancedMetrics();
430 if (result && result->fPostScriptName.isEmpty()) {
431 result->fPostScriptName = result->fFontName;
432 }
433 if (result && result->fType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
434 SkOTTableOS2::Version::V2::Type::Field fsType;
435 constexpr SkFontTableTag os2Tag = SkTEndian_SwapBE32(SkOTTableOS2::TAG);
436 constexpr size_t fsTypeOffset = offsetof(SkOTTableOS2::Version::V2, fsType);
437 if (this->getTableData(os2Tag, fsTypeOffset, sizeof(fsType), &fsType) == sizeof(fsType)) {
438 if (fsType.Bitmap || (fsType.Restricted && !(fsType.PreviewPrint || fsType.Editable))) {
439 result->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
440 }
441 if (fsType.NoSubsetting) {
442 result->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
443 }
444 }
445 }
446 return result;
447 }
448
onGetKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const449 bool SkTypeface::onGetKerningPairAdjustments(const uint16_t glyphs[], int count,
450 int32_t adjustments[]) const {
451 return false;
452 }
453
454 ///////////////////////////////////////////////////////////////////////////////
455
456 #include "include/core/SkPaint.h"
457 #include "src/core/SkDescriptor.h"
458
getBounds() const459 SkRect SkTypeface::getBounds() const {
460 fBoundsOnce([this] {
461 if (!this->onComputeBounds(&fBounds)) {
462 fBounds.setEmpty();
463 }
464 });
465 return fBounds;
466 }
467
onComputeBounds(SkRect * bounds) const468 bool SkTypeface::onComputeBounds(SkRect* bounds) const {
469 // we use a big size to ensure lots of significant bits from the scalercontext.
470 // then we scale back down to return our final answer (at 1-pt)
471 const SkScalar textSize = 2048;
472 const SkScalar invTextSize = 1 / textSize;
473
474 SkFont font;
475 font.setTypeface(sk_ref_sp(const_cast<SkTypeface*>(this)));
476 font.setSize(textSize);
477 font.setLinearMetrics(true);
478
479 SkScalerContextRec rec;
480 SkScalerContextEffects effects;
481
482 SkScalerContext::MakeRecAndEffectsFromFont(font, &rec, &effects);
483
484 SkAutoDescriptor ad;
485 SkScalerContextEffects noeffects;
486 SkScalerContext::AutoDescriptorGivenRecAndEffects(rec, noeffects, &ad);
487
488 std::unique_ptr<SkScalerContext> ctx = this->createScalerContext(noeffects, ad.getDesc());
489
490 SkFontMetrics fm;
491 ctx->getFontMetrics(&fm);
492 if (!fm.hasBounds()) {
493 return false;
494 }
495 bounds->setLTRB(fm.fXMin * invTextSize, fm.fTop * invTextSize,
496 fm.fXMax * invTextSize, fm.fBottom * invTextSize);
497 return true;
498 }
499
onGetAdvancedMetrics() const500 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface::onGetAdvancedMetrics() const {
501 SkDEBUGFAIL("Typefaces that need to work with PDF backend must override this.");
502 return nullptr;
503 }
504