• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "SkAdvancedTypefaceMetrics.h"
9 #include "SkEndian.h"
10 #include "SkFontDescriptor.h"
11 #include "SkFontMetrics.h"
12 #include "SkFontMgr.h"
13 #include "SkMakeUnique.h"
14 #include "SkMutex.h"
15 #include "SkOTTable_OS_2.h"
16 #include "SkOnce.h"
17 #include "SkStream.h"
18 #include "SkSurfacePriv.h"
19 #include "SkTypeface.h"
20 #include "SkTypefaceCache.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     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 void * chars,Encoding encoding,uint16_t glyphs[],int glyphCount) const60     virtual int onCharsToGlyphs(const void* chars, Encoding encoding,
61                                 uint16_t glyphs[], int glyphCount) const override {
62         if (glyphs && glyphCount > 0) {
63             sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
64         }
65         return 0;
66     }
onCountGlyphs() const67     int onCountGlyphs() const override { return 0; }
onGetUPEM() const68     int onGetUPEM() const override { return 0; }
69     class EmptyLocalizedStrings : public SkTypeface::LocalizedStrings {
70     public:
next(SkTypeface::LocalizedString *)71         bool next(SkTypeface::LocalizedString*) override { return false; }
72     };
onGetFamilyName(SkString * familyName) const73     void onGetFamilyName(SkString* familyName) const override {
74         familyName->reset();
75     }
onCreateFamilyNameIterator() const76     SkTypeface::LocalizedStrings* onCreateFamilyNameIterator() const override {
77         return new EmptyLocalizedStrings;
78     }
onGetVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],int coordinateCount) const79     int onGetVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],
80                                      int coordinateCount) const override
81     {
82         return 0;
83     }
onGetVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],int parameterCount) const84     int onGetVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],
85                                        int parameterCount) const override
86     {
87         return 0;
88     }
onGetTableTags(SkFontTableTag tags[]) const89     int onGetTableTags(SkFontTableTag tags[]) const override { return 0; }
onGetTableData(SkFontTableTag,size_t,size_t,void *) const90     size_t onGetTableData(SkFontTableTag, size_t, size_t, void*) const override {
91         return 0;
92     }
93 };
94 
95 }  // namespace
96 
FromOldStyle(Style oldStyle)97 SkFontStyle SkTypeface::FromOldStyle(Style oldStyle) {
98     return SkFontStyle((oldStyle & SkTypeface::kBold) ? SkFontStyle::kBold_Weight
99                                                       : SkFontStyle::kNormal_Weight,
100                        SkFontStyle::kNormal_Width,
101                        (oldStyle & SkTypeface::kItalic) ? SkFontStyle::kItalic_Slant
102                                                         : SkFontStyle::kUpright_Slant);
103 }
104 
GetDefaultTypeface(Style style)105 SkTypeface* SkTypeface::GetDefaultTypeface(Style style) {
106     static SkOnce once[4];
107     static sk_sp<SkTypeface> defaults[4];
108 
109     SkASSERT((int)style < 4);
110     once[style]([style] {
111         sk_sp<SkFontMgr> fm(SkFontMgr::RefDefault());
112         auto t = fm->legacyMakeTypeface(nullptr, FromOldStyle(style));
113         defaults[style] = t ? t : SkEmptyTypeface::Make();
114     });
115     return defaults[style].get();
116 }
117 
MakeDefault()118 sk_sp<SkTypeface> SkTypeface::MakeDefault() {
119     return sk_ref_sp(GetDefaultTypeface());
120 }
121 
UniqueID(const SkTypeface * face)122 uint32_t SkTypeface::UniqueID(const SkTypeface* face) {
123     if (nullptr == face) {
124         face = GetDefaultTypeface();
125     }
126     return face->uniqueID();
127 }
128 
Equal(const SkTypeface * facea,const SkTypeface * faceb)129 bool SkTypeface::Equal(const SkTypeface* facea, const SkTypeface* faceb) {
130     return facea == faceb || SkTypeface::UniqueID(facea) == SkTypeface::UniqueID(faceb);
131 }
132 
133 ///////////////////////////////////////////////////////////////////////////////
134 
MakeFromName(const char name[],SkFontStyle fontStyle)135 sk_sp<SkTypeface> SkTypeface::MakeFromName(const char name[],
136                                            SkFontStyle fontStyle) {
137     if (nullptr == name && (fontStyle.slant() == SkFontStyle::kItalic_Slant ||
138                             fontStyle.slant() == SkFontStyle::kUpright_Slant) &&
139                            (fontStyle.weight() == SkFontStyle::kBold_Weight ||
140                             fontStyle.weight() == SkFontStyle::kNormal_Weight)) {
141         return sk_ref_sp(GetDefaultTypeface(static_cast<SkTypeface::Style>(
142             (fontStyle.slant() == SkFontStyle::kItalic_Slant ? SkTypeface::kItalic :
143                                                                SkTypeface::kNormal) |
144             (fontStyle.weight() == SkFontStyle::kBold_Weight ? SkTypeface::kBold :
145                                                                SkTypeface::kNormal))));
146     }
147     return SkFontMgr::RefDefault()->legacyMakeTypeface(name, fontStyle);
148 }
149 
MakeFromStream(std::unique_ptr<SkStreamAsset> stream,int index)150 sk_sp<SkTypeface> SkTypeface::MakeFromStream(std::unique_ptr<SkStreamAsset> stream, int index) {
151     if (!stream) {
152         return nullptr;
153     }
154     return SkFontMgr::RefDefault()->makeFromStream(std::move(stream), index);
155 }
156 
MakeFromData(sk_sp<SkData> data,int index)157 sk_sp<SkTypeface> SkTypeface::MakeFromData(sk_sp<SkData> data, int index) {
158     if (!data) {
159         return nullptr;
160     }
161     return SkFontMgr::RefDefault()->makeFromData(std::move(data), index);
162 }
163 
MakeFromFontData(std::unique_ptr<SkFontData> data)164 sk_sp<SkTypeface> SkTypeface::MakeFromFontData(std::unique_ptr<SkFontData> data) {
165     return SkFontMgr::RefDefault()->makeFromFontData(std::move(data));
166 }
167 
MakeFromFile(const char path[],int index)168 sk_sp<SkTypeface> SkTypeface::MakeFromFile(const char path[], int index) {
169     return SkFontMgr::RefDefault()->makeFromFile(path, index);
170 }
171 
makeClone(const SkFontArguments & args) const172 sk_sp<SkTypeface> SkTypeface::makeClone(const SkFontArguments& args) const {
173     return this->onMakeClone(args);
174 }
175 
176 ///////////////////////////////////////////////////////////////////////////////
177 
serialize(SkWStream * wstream,SerializeBehavior behavior) const178 void SkTypeface::serialize(SkWStream* wstream, SerializeBehavior behavior) const {
179     if (gSerializeTypefaceDelegate) {
180         (*gSerializeTypefaceDelegate)(this, wstream);
181         return;
182     }
183     bool isLocalData = false;
184     SkFontDescriptor desc;
185     this->onGetFontDescriptor(&desc, &isLocalData);
186 
187     switch (behavior) {
188         case SerializeBehavior::kDoIncludeData:
189             isLocalData = true;
190             break;
191         case SerializeBehavior::kDontIncludeData:
192             isLocalData = false;
193             break;
194         case SerializeBehavior::kIncludeDataIfLocal:
195             break;
196     }
197 
198     // TODO: why do we check hasFontData() and allow the data to pass through even if the caller
199     //       has said they don't want the fontdata? Does this actually happen (getDescriptor returns
200     //       fontdata as well?)
201     if (isLocalData && !desc.hasFontData()) {
202         desc.setFontData(this->onMakeFontData());
203     }
204     desc.serialize(wstream);
205 }
206 
serialize(SerializeBehavior behavior) const207 sk_sp<SkData> SkTypeface::serialize(SerializeBehavior behavior) const {
208     SkDynamicMemoryWStream stream;
209     this->serialize(&stream, behavior);
210     return stream.detachAsData();
211 }
212 
MakeDeserialize(SkStream * stream)213 sk_sp<SkTypeface> SkTypeface::MakeDeserialize(SkStream* stream) {
214     if (gDeserializeTypefaceDelegate) {
215         return (*gDeserializeTypefaceDelegate)(stream);
216     }
217 
218     SkFontDescriptor desc;
219     if (!SkFontDescriptor::Deserialize(stream, &desc)) {
220         return nullptr;
221     }
222 
223     std::unique_ptr<SkFontData> data = desc.detachFontData();
224     if (data) {
225         sk_sp<SkTypeface> typeface(SkTypeface::MakeFromFontData(std::move(data)));
226         if (typeface) {
227             return typeface;
228         }
229     }
230 
231     return SkTypeface::MakeFromName(desc.getFamilyName(), desc.getStyle());
232 }
233 
234 ///////////////////////////////////////////////////////////////////////////////
235 
getVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],int coordinateCount) const236 int SkTypeface::getVariationDesignPosition(
237         SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
238 {
239     return this->onGetVariationDesignPosition(coordinates, coordinateCount);
240 }
241 
getVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],int parameterCount) const242 int SkTypeface::getVariationDesignParameters(
243         SkFontParameters::Variation::Axis parameters[], int parameterCount) const
244 {
245     return this->onGetVariationDesignParameters(parameters, parameterCount);
246 }
247 
countTables() const248 int SkTypeface::countTables() const {
249     return this->onGetTableTags(nullptr);
250 }
251 
getTableTags(SkFontTableTag tags[]) const252 int SkTypeface::getTableTags(SkFontTableTag tags[]) const {
253     return this->onGetTableTags(tags);
254 }
255 
getTableSize(SkFontTableTag tag) const256 size_t SkTypeface::getTableSize(SkFontTableTag tag) const {
257     return this->onGetTableData(tag, 0, ~0U, nullptr);
258 }
259 
getTableData(SkFontTableTag tag,size_t offset,size_t length,void * data) const260 size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length,
261                                 void* data) const {
262     return this->onGetTableData(tag, offset, length, data);
263 }
264 
openStream(int * ttcIndex) const265 SkStreamAsset* SkTypeface::openStream(int* ttcIndex) const {
266     int ttcIndexStorage;
267     if (nullptr == ttcIndex) {
268         // So our subclasses don't need to check for null param
269         ttcIndex = &ttcIndexStorage;
270     }
271     return this->onOpenStream(ttcIndex);
272 }
273 
makeFontData() const274 std::unique_ptr<SkFontData> SkTypeface::makeFontData() const {
275     return this->onMakeFontData();
276 }
277 
278 // This implementation is temporary until this method can be made pure virtual.
onMakeFontData() const279 std::unique_ptr<SkFontData> SkTypeface::onMakeFontData() const {
280     int index;
281     std::unique_ptr<SkStreamAsset> stream(this->onOpenStream(&index));
282     if (!stream) {
283         return nullptr;
284     }
285     return skstd::make_unique<SkFontData>(std::move(stream), index, nullptr, 0);
286 };
287 
charsToGlyphs(const void * chars,Encoding encoding,uint16_t glyphs[],int glyphCount) const288 int SkTypeface::charsToGlyphs(const void* chars, Encoding encoding,
289                               uint16_t glyphs[], int glyphCount) const {
290     if (glyphCount <= 0) {
291         return 0;
292     }
293     if (nullptr == chars || (unsigned)encoding > kUTF32_Encoding) {
294         if (glyphs) {
295             sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
296         }
297         return 0;
298     }
299     return this->onCharsToGlyphs(chars, encoding, glyphs, glyphCount);
300 }
301 
unicharToGlyph(SkUnichar uni) const302 SkGlyphID SkTypeface::unicharToGlyph(SkUnichar uni) const {
303     SkGlyphID glyphs[1];
304     return this->onCharsToGlyphs(&uni, kUTF32_Encoding, glyphs, 1) == 1 ? glyphs[0] : 0;
305 }
306 
countGlyphs() const307 int SkTypeface::countGlyphs() const {
308     return this->onCountGlyphs();
309 }
310 
getUnitsPerEm() const311 int SkTypeface::getUnitsPerEm() const {
312     // should we try to cache this in the base-class?
313     return this->onGetUPEM();
314 }
315 
getKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const316 bool SkTypeface::getKerningPairAdjustments(const uint16_t glyphs[], int count,
317                                            int32_t adjustments[]) const {
318     SkASSERT(count >= 0);
319     // check for the only legal way to pass a nullptr.. everything is 0
320     // in which case they just want to know if this face can possibly support
321     // kerning (true) or never (false).
322     if (nullptr == glyphs || nullptr == adjustments) {
323         SkASSERT(nullptr == glyphs);
324         SkASSERT(0 == count);
325         SkASSERT(nullptr == adjustments);
326     }
327     return this->onGetKerningPairAdjustments(glyphs, count, adjustments);
328 }
329 
createFamilyNameIterator() const330 SkTypeface::LocalizedStrings* SkTypeface::createFamilyNameIterator() const {
331     return this->onCreateFamilyNameIterator();
332 }
333 
getFamilyName(SkString * name) const334 void SkTypeface::getFamilyName(SkString* name) const {
335     SkASSERT(name);
336     this->onGetFamilyName(name);
337 }
338 
getGlyphToUnicodeMap(SkUnichar * dst) const339 void SkTypeface::getGlyphToUnicodeMap(SkUnichar* dst) const {
340     sk_bzero(dst, sizeof(SkUnichar) * this->countGlyphs());
341 }
342 
getAdvancedMetrics() const343 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface::getAdvancedMetrics() const {
344     std::unique_ptr<SkAdvancedTypefaceMetrics> result = this->onGetAdvancedMetrics();
345     if (result && result->fPostScriptName.isEmpty()) {
346         result->fPostScriptName = result->fFontName;
347     }
348     if (result && result->fType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
349         SkOTTableOS2::Version::V2::Type::Field fsType;
350         constexpr SkFontTableTag os2Tag = SkTEndian_SwapBE32(SkOTTableOS2::TAG);
351         constexpr size_t fsTypeOffset = offsetof(SkOTTableOS2::Version::V2, fsType);
352         if (this->getTableData(os2Tag, fsTypeOffset, sizeof(fsType), &fsType) == sizeof(fsType)) {
353             if (fsType.Bitmap || (fsType.Restricted && !(fsType.PreviewPrint || fsType.Editable))) {
354                 result->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
355             }
356             if (fsType.NoSubsetting) {
357                 result->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
358             }
359         }
360     }
361     return result;
362 }
363 
onGetKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const364 bool SkTypeface::onGetKerningPairAdjustments(const uint16_t glyphs[], int count,
365                                              int32_t adjustments[]) const {
366     return false;
367 }
368 
onMakeClone(const SkFontArguments & args) const369 sk_sp<SkTypeface> SkTypeface::onMakeClone(const SkFontArguments& args) const {
370     return sk_ref_sp(this);
371 }
372 
onGetVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],int parameterCount) const373 int SkTypeface::onGetVariationDesignParameters(
374         SkFontParameters::Variation::Axis parameters[], int parameterCount) const {
375     return -1;
376 }
377 
378 ///////////////////////////////////////////////////////////////////////////////
379 
380 #include "SkDescriptor.h"
381 #include "SkPaint.h"
382 
getBounds() const383 SkRect SkTypeface::getBounds() const {
384     fBoundsOnce([this] {
385         if (!this->onComputeBounds(&fBounds)) {
386             fBounds.setEmpty();
387         }
388     });
389     return fBounds;
390 }
391 
onComputeBounds(SkRect * bounds) const392 bool SkTypeface::onComputeBounds(SkRect* bounds) const {
393     // we use a big size to ensure lots of significant bits from the scalercontext.
394     // then we scale back down to return our final answer (at 1-pt)
395     const SkScalar textSize = 2048;
396     const SkScalar invTextSize = 1 / textSize;
397 
398     SkFont font;
399     font.setTypeface(sk_ref_sp(const_cast<SkTypeface*>(this)));
400     font.setSize(textSize);
401     font.setLinearMetrics(true);
402 
403     SkScalerContextRec rec;
404     SkScalerContextEffects effects;
405 
406     SkScalerContext::MakeRecAndEffectsFromFont(font, &rec, &effects);
407 
408     SkAutoDescriptor ad;
409     SkScalerContextEffects noeffects;
410     SkScalerContext::AutoDescriptorGivenRecAndEffects(rec, noeffects, &ad);
411 
412     std::unique_ptr<SkScalerContext> ctx = this->createScalerContext(noeffects, ad.getDesc(), true);
413     if (!ctx) {
414         return false;
415     }
416 
417     SkFontMetrics fm;
418     ctx->getFontMetrics(&fm);
419     bounds->set(fm.fXMin * invTextSize, fm.fTop * invTextSize,
420                 fm.fXMax * invTextSize, fm.fBottom * invTextSize);
421     return true;
422 }
423 
onGetAdvancedMetrics() const424 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface::onGetAdvancedMetrics() const {
425     SkDEBUGFAIL("Typefaces that need to work with PDF backend must override this.");
426     return nullptr;
427 }
428