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