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 "src/core/SkAdvancedTypefaceMetrics.h"
15 #include "src/core/SkEndian.h"
16 #include "src/core/SkFontDescriptor.h"
17 #include "src/core/SkMakeUnique.h"
18 #include "src/core/SkSurfacePriv.h"
19 #include "src/core/SkTypefaceCache.h"
20 #include "src/sfnt/SkOTTable_OS_2.h"
21 
SkTypeface(const SkFontStyle & style,bool isFixedPitch)22 SkTypeface::SkTypeface(const SkFontStyle& style, bool isFixedPitch)
23     : fUniqueID(SkTypefaceCache::NewFontID()), fStyle(style), fIsFixedPitch(isFixedPitch) { }
24 
~SkTypeface()25 SkTypeface::~SkTypeface() { }
26 
27 #ifdef SK_WHITELIST_SERIALIZED_TYPEFACES
28 extern void WhitelistSerializeTypeface(const SkTypeface*, SkWStream* );
29 #define SK_TYPEFACE_DELEGATE WhitelistSerializeTypeface
30 #else
31 #define SK_TYPEFACE_DELEGATE nullptr
32 #endif
33 
34 void (*gSerializeTypefaceDelegate)(const SkTypeface*, SkWStream* ) = SK_TYPEFACE_DELEGATE;
35 sk_sp<SkTypeface> (*gDeserializeTypefaceDelegate)(SkStream* ) = nullptr;
36 
37 ///////////////////////////////////////////////////////////////////////////////
38 
39 namespace {
40 
41 class SkEmptyTypeface : public SkTypeface {
42 public:
Make()43     static sk_sp<SkTypeface> Make() { return sk_sp<SkTypeface>(new SkEmptyTypeface); }
44 protected:
SkEmptyTypeface()45     SkEmptyTypeface() : SkTypeface(SkFontStyle(), true) { }
46 
onOpenStream(int * ttcIndex) const47     std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const override { return nullptr; }
onMakeClone(const SkFontArguments & args) const48     sk_sp<SkTypeface> onMakeClone(const SkFontArguments& args) const override {
49         return sk_ref_sp(this);
50     }
onCreateScalerContext(const SkScalerContextEffects &,const SkDescriptor *) const51     SkScalerContext* onCreateScalerContext(const SkScalerContextEffects&,
52                                            const SkDescriptor*) const override {
53         return nullptr;
54     }
onFilterRec(SkScalerContextRec *) const55     void onFilterRec(SkScalerContextRec*) const override { }
onGetAdvancedMetrics() const56     std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const override {
57         return nullptr;
58     }
onGetFontDescriptor(SkFontDescriptor *,bool *) const59     void onGetFontDescriptor(SkFontDescriptor*, bool*) const override { }
onCharsToGlyphs(const SkUnichar * chars,int count,SkGlyphID glyphs[]) const60     void onCharsToGlyphs(const SkUnichar* chars, int count, SkGlyphID glyphs[]) const override {
61         sk_bzero(glyphs, count * sizeof(glyphs[0]));
62     }
onCountGlyphs() const63     int onCountGlyphs() const override { return 0; }
getPostScriptGlyphNames(SkString *) const64     void getPostScriptGlyphNames(SkString*) const override {}
getGlyphToUnicodeMap(SkUnichar *) const65     void getGlyphToUnicodeMap(SkUnichar*) const override {}
onGetUPEM() const66     int onGetUPEM() const override { return 0; }
67     class EmptyLocalizedStrings : public SkTypeface::LocalizedStrings {
68     public:
next(SkTypeface::LocalizedString *)69         bool next(SkTypeface::LocalizedString*) override { return false; }
70     };
onGetFamilyName(SkString * familyName) const71     void onGetFamilyName(SkString* familyName) const override {
72         familyName->reset();
73     }
onCreateFamilyNameIterator() const74     SkTypeface::LocalizedStrings* onCreateFamilyNameIterator() const override {
75         return new EmptyLocalizedStrings;
76     }
onGetVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],int coordinateCount) const77     int onGetVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],
78                                      int coordinateCount) const override
79     {
80         return 0;
81     }
onGetVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],int parameterCount) const82     int onGetVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],
83                                        int parameterCount) const override
84     {
85         return 0;
86     }
onGetTableTags(SkFontTableTag tags[]) const87     int onGetTableTags(SkFontTableTag tags[]) const override { return 0; }
onGetTableData(SkFontTableTag,size_t,size_t,void *) const88     size_t onGetTableData(SkFontTableTag, size_t, size_t, void*) const override {
89         return 0;
90     }
91 };
92 
93 }  // namespace
94 
FromOldStyle(Style oldStyle)95 SkFontStyle SkTypeface::FromOldStyle(Style oldStyle) {
96     return SkFontStyle((oldStyle & SkTypeface::kBold) ? SkFontStyle::kBold_Weight
97                                                       : SkFontStyle::kNormal_Weight,
98                        SkFontStyle::kNormal_Width,
99                        (oldStyle & SkTypeface::kItalic) ? SkFontStyle::kItalic_Slant
100                                                         : SkFontStyle::kUpright_Slant);
101 }
102 
GetDefaultTypeface(Style style)103 SkTypeface* SkTypeface::GetDefaultTypeface(Style style) {
104     static SkOnce once[4];
105     static sk_sp<SkTypeface> defaults[4];
106 
107     SkASSERT((int)style < 4);
108     once[style]([style] {
109         sk_sp<SkFontMgr> fm(SkFontMgr::RefDefault());
110         auto t = fm->legacyMakeTypeface(nullptr, FromOldStyle(style));
111         defaults[style] = t ? t : SkEmptyTypeface::Make();
112     });
113     return defaults[style].get();
114 }
115 
MakeDefault()116 sk_sp<SkTypeface> SkTypeface::MakeDefault() {
117     return sk_ref_sp(GetDefaultTypeface());
118 }
119 
UniqueID(const SkTypeface * face)120 uint32_t SkTypeface::UniqueID(const SkTypeface* face) {
121     if (nullptr == face) {
122         face = GetDefaultTypeface();
123     }
124     return face->uniqueID();
125 }
126 
Equal(const SkTypeface * facea,const SkTypeface * faceb)127 bool SkTypeface::Equal(const SkTypeface* facea, const SkTypeface* faceb) {
128     return facea == faceb || SkTypeface::UniqueID(facea) == SkTypeface::UniqueID(faceb);
129 }
130 
131 ///////////////////////////////////////////////////////////////////////////////
132 
MakeFromName(const char name[],SkFontStyle fontStyle)133 sk_sp<SkTypeface> SkTypeface::MakeFromName(const char name[],
134                                            SkFontStyle fontStyle) {
135     if (nullptr == name && (fontStyle.slant() == SkFontStyle::kItalic_Slant ||
136                             fontStyle.slant() == SkFontStyle::kUpright_Slant) &&
137                            (fontStyle.weight() == SkFontStyle::kBold_Weight ||
138                             fontStyle.weight() == SkFontStyle::kNormal_Weight)) {
139         return sk_ref_sp(GetDefaultTypeface(static_cast<SkTypeface::Style>(
140             (fontStyle.slant() == SkFontStyle::kItalic_Slant ? SkTypeface::kItalic :
141                                                                SkTypeface::kNormal) |
142             (fontStyle.weight() == SkFontStyle::kBold_Weight ? SkTypeface::kBold :
143                                                                SkTypeface::kNormal))));
144     }
145     return SkFontMgr::RefDefault()->legacyMakeTypeface(name, fontStyle);
146 }
147 
MakeFromStream(std::unique_ptr<SkStreamAsset> stream,int index)148 sk_sp<SkTypeface> SkTypeface::MakeFromStream(std::unique_ptr<SkStreamAsset> stream, int index) {
149     if (!stream) {
150         return nullptr;
151     }
152     return SkFontMgr::RefDefault()->makeFromStream(std::move(stream), index);
153 }
154 
MakeFromData(sk_sp<SkData> data,int index)155 sk_sp<SkTypeface> SkTypeface::MakeFromData(sk_sp<SkData> data, int index) {
156     if (!data) {
157         return nullptr;
158     }
159     return SkFontMgr::RefDefault()->makeFromData(std::move(data), index);
160 }
161 
MakeFromFontData(std::unique_ptr<SkFontData> data)162 sk_sp<SkTypeface> SkTypeface::MakeFromFontData(std::unique_ptr<SkFontData> data) {
163     return SkFontMgr::RefDefault()->makeFromFontData(std::move(data));
164 }
165 
MakeFromFile(const char path[],int index)166 sk_sp<SkTypeface> SkTypeface::MakeFromFile(const char path[], int index) {
167     return SkFontMgr::RefDefault()->makeFromFile(path, index);
168 }
169 
makeClone(const SkFontArguments & args) const170 sk_sp<SkTypeface> SkTypeface::makeClone(const SkFontArguments& args) const {
171     return this->onMakeClone(args);
172 }
173 
174 ///////////////////////////////////////////////////////////////////////////////
175 
serialize(SkWStream * wstream,SerializeBehavior behavior) const176 void SkTypeface::serialize(SkWStream* wstream, SerializeBehavior behavior) const {
177     if (gSerializeTypefaceDelegate) {
178         (*gSerializeTypefaceDelegate)(this, wstream);
179         return;
180     }
181 
182     bool isLocalData = false;
183     SkFontDescriptor desc;
184     this->onGetFontDescriptor(&desc, &isLocalData);
185 
186     bool shouldSerializeData = false;
187     switch (behavior) {
188         case SerializeBehavior::kDoIncludeData:      shouldSerializeData = true;        break;
189         case SerializeBehavior::kDontIncludeData:    shouldSerializeData = false;       break;
190         case SerializeBehavior::kIncludeDataIfLocal: shouldSerializeData = isLocalData; break;
191     }
192 
193     // TODO: why do we check hasFontData() and allow the data to pass through even if the caller
194     //       has said they don't want the fontdata? Does this actually happen (getDescriptor returns
195     //       fontdata as well?)
196     if (shouldSerializeData && !desc.hasFontData()) {
197         desc.setFontData(this->onMakeFontData());
198     }
199     desc.serialize(wstream);
200 }
201 
serialize(SerializeBehavior behavior) const202 sk_sp<SkData> SkTypeface::serialize(SerializeBehavior behavior) const {
203     SkDynamicMemoryWStream stream;
204     this->serialize(&stream, behavior);
205     return stream.detachAsData();
206 }
207 
MakeDeserialize(SkStream * stream)208 sk_sp<SkTypeface> SkTypeface::MakeDeserialize(SkStream* stream) {
209     if (gDeserializeTypefaceDelegate) {
210         return (*gDeserializeTypefaceDelegate)(stream);
211     }
212 
213     SkFontDescriptor desc;
214     if (!SkFontDescriptor::Deserialize(stream, &desc)) {
215         return nullptr;
216     }
217 
218     std::unique_ptr<SkFontData> data = desc.detachFontData();
219     if (data) {
220         sk_sp<SkTypeface> typeface(SkTypeface::MakeFromFontData(std::move(data)));
221         if (typeface) {
222             return typeface;
223         }
224     }
225 
226     return SkTypeface::MakeFromName(desc.getFamilyName(), desc.getStyle());
227 }
228 
229 ///////////////////////////////////////////////////////////////////////////////
230 
getVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],int coordinateCount) const231 int SkTypeface::getVariationDesignPosition(
232         SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
233 {
234     return this->onGetVariationDesignPosition(coordinates, coordinateCount);
235 }
236 
getVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],int parameterCount) const237 int SkTypeface::getVariationDesignParameters(
238         SkFontParameters::Variation::Axis parameters[], int parameterCount) const
239 {
240     return this->onGetVariationDesignParameters(parameters, parameterCount);
241 }
242 
countTables() const243 int SkTypeface::countTables() const {
244     return this->onGetTableTags(nullptr);
245 }
246 
getTableTags(SkFontTableTag tags[]) const247 int SkTypeface::getTableTags(SkFontTableTag tags[]) const {
248     return this->onGetTableTags(tags);
249 }
250 
getTableSize(SkFontTableTag tag) const251 size_t SkTypeface::getTableSize(SkFontTableTag tag) const {
252     return this->onGetTableData(tag, 0, ~0U, nullptr);
253 }
254 
getTableData(SkFontTableTag tag,size_t offset,size_t length,void * data) const255 size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length,
256                                 void* data) const {
257     return this->onGetTableData(tag, offset, length, data);
258 }
259 
copyTableData(SkFontTableTag tag) const260 sk_sp<SkData> SkTypeface::copyTableData(SkFontTableTag tag) const {
261     return this->onCopyTableData(tag);
262 }
263 
onCopyTableData(SkFontTableTag tag) const264 sk_sp<SkData> SkTypeface::onCopyTableData(SkFontTableTag tag) const {
265     size_t size = this->getTableSize(tag);
266     if (size) {
267         sk_sp<SkData> data = SkData::MakeUninitialized(size);
268         (void)this->getTableData(tag, 0, size, data->writable_data());
269         return data;
270     }
271     return nullptr;
272 }
273 
openStream(int * ttcIndex) const274 std::unique_ptr<SkStreamAsset> SkTypeface::openStream(int* ttcIndex) const {
275     int ttcIndexStorage;
276     if (nullptr == ttcIndex) {
277         // So our subclasses don't need to check for null param
278         ttcIndex = &ttcIndexStorage;
279     }
280     return this->onOpenStream(ttcIndex);
281 }
282 
makeFontData() const283 std::unique_ptr<SkFontData> SkTypeface::makeFontData() const {
284     return this->onMakeFontData();
285 }
286 
287 // This implementation is temporary until this method can be made pure virtual.
onMakeFontData() const288 std::unique_ptr<SkFontData> SkTypeface::onMakeFontData() const {
289     int index;
290     std::unique_ptr<SkStreamAsset> stream(this->onOpenStream(&index));
291     if (!stream) {
292         return nullptr;
293     }
294     return skstd::make_unique<SkFontData>(std::move(stream), index, nullptr, 0);
295 };
296 
unicharsToGlyphs(const SkUnichar uni[],int count,SkGlyphID glyphs[]) const297 void SkTypeface::unicharsToGlyphs(const SkUnichar uni[], int count, SkGlyphID glyphs[]) const {
298     if (count > 0 && glyphs && uni) {
299         this->onCharsToGlyphs(uni, count, glyphs);
300     }
301 }
302 
unicharToGlyph(SkUnichar uni) const303 SkGlyphID SkTypeface::unicharToGlyph(SkUnichar uni) const {
304     SkGlyphID glyphs[1] = { 0 };
305     this->onCharsToGlyphs(&uni, 1, glyphs);
306     return glyphs[0];
307 }
308 
countGlyphs() const309 int SkTypeface::countGlyphs() const {
310     return this->onCountGlyphs();
311 }
312 
getUnitsPerEm() const313 int SkTypeface::getUnitsPerEm() const {
314     // should we try to cache this in the base-class?
315     return this->onGetUPEM();
316 }
317 
getKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const318 bool SkTypeface::getKerningPairAdjustments(const uint16_t glyphs[], int count,
319                                            int32_t adjustments[]) const {
320     SkASSERT(count >= 0);
321     // check for the only legal way to pass a nullptr.. everything is 0
322     // in which case they just want to know if this face can possibly support
323     // kerning (true) or never (false).
324     if (nullptr == glyphs || nullptr == adjustments) {
325         SkASSERT(nullptr == glyphs);
326         SkASSERT(0 == count);
327         SkASSERT(nullptr == adjustments);
328     }
329     return this->onGetKerningPairAdjustments(glyphs, count, adjustments);
330 }
331 
createFamilyNameIterator() const332 SkTypeface::LocalizedStrings* SkTypeface::createFamilyNameIterator() const {
333     return this->onCreateFamilyNameIterator();
334 }
335 
getFamilyName(SkString * name) const336 void SkTypeface::getFamilyName(SkString* name) const {
337     SkASSERT(name);
338     this->onGetFamilyName(name);
339 }
340 
getGlyphToUnicodeMap(SkUnichar * dst) const341 void SkTypeface::getGlyphToUnicodeMap(SkUnichar* dst) const {
342     sk_bzero(dst, sizeof(SkUnichar) * this->countGlyphs());
343 }
344 
getAdvancedMetrics() const345 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface::getAdvancedMetrics() const {
346     std::unique_ptr<SkAdvancedTypefaceMetrics> result = this->onGetAdvancedMetrics();
347     if (result && result->fPostScriptName.isEmpty()) {
348         result->fPostScriptName = result->fFontName;
349     }
350     if (result && result->fType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
351         SkOTTableOS2::Version::V2::Type::Field fsType;
352         constexpr SkFontTableTag os2Tag = SkTEndian_SwapBE32(SkOTTableOS2::TAG);
353         constexpr size_t fsTypeOffset = offsetof(SkOTTableOS2::Version::V2, fsType);
354         if (this->getTableData(os2Tag, fsTypeOffset, sizeof(fsType), &fsType) == sizeof(fsType)) {
355             if (fsType.Bitmap || (fsType.Restricted && !(fsType.PreviewPrint || fsType.Editable))) {
356                 result->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
357             }
358             if (fsType.NoSubsetting) {
359                 result->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
360             }
361         }
362     }
363     return result;
364 }
365 
onGetKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const366 bool SkTypeface::onGetKerningPairAdjustments(const uint16_t glyphs[], int count,
367                                              int32_t adjustments[]) const {
368     return false;
369 }
370 
371 ///////////////////////////////////////////////////////////////////////////////
372 
373 #include "include/core/SkPaint.h"
374 #include "src/core/SkDescriptor.h"
375 
getBounds() const376 SkRect SkTypeface::getBounds() const {
377     fBoundsOnce([this] {
378         if (!this->onComputeBounds(&fBounds)) {
379             fBounds.setEmpty();
380         }
381     });
382     return fBounds;
383 }
384 
onComputeBounds(SkRect * bounds) const385 bool SkTypeface::onComputeBounds(SkRect* bounds) const {
386     // we use a big size to ensure lots of significant bits from the scalercontext.
387     // then we scale back down to return our final answer (at 1-pt)
388     const SkScalar textSize = 2048;
389     const SkScalar invTextSize = 1 / textSize;
390 
391     SkFont font;
392     font.setTypeface(sk_ref_sp(const_cast<SkTypeface*>(this)));
393     font.setSize(textSize);
394     font.setLinearMetrics(true);
395 
396     SkScalerContextRec rec;
397     SkScalerContextEffects effects;
398 
399     SkScalerContext::MakeRecAndEffectsFromFont(font, &rec, &effects);
400 
401     SkAutoDescriptor ad;
402     SkScalerContextEffects noeffects;
403     SkScalerContext::AutoDescriptorGivenRecAndEffects(rec, noeffects, &ad);
404 
405     std::unique_ptr<SkScalerContext> ctx = this->createScalerContext(noeffects, ad.getDesc(), true);
406     if (!ctx) {
407         return false;
408     }
409 
410     SkFontMetrics fm;
411     ctx->getFontMetrics(&fm);
412     bounds->setLTRB(fm.fXMin * invTextSize, fm.fTop * invTextSize,
413                     fm.fXMax * invTextSize, fm.fBottom * invTextSize);
414     return true;
415 }
416 
onGetAdvancedMetrics() const417 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface::onGetAdvancedMetrics() const {
418     SkDEBUGFAIL("Typefaces that need to work with PDF backend must override this.");
419     return nullptr;
420 }
421