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 "SkFontMgr.h"
12 #include "SkMutex.h"
13 #include "SkOTTable_OS_2.h"
14 #include "SkOncePtr.h"
15 #include "SkStream.h"
16 #include "SkTypeface.h"
17 
SkTypeface(const SkFontStyle & style,SkFontID fontID,bool isFixedPitch)18 SkTypeface::SkTypeface(const SkFontStyle& style, SkFontID fontID, bool isFixedPitch)
19     : fUniqueID(fontID), fStyle(style), fIsFixedPitch(isFixedPitch) { }
20 
~SkTypeface()21 SkTypeface::~SkTypeface() { }
22 
23 #ifdef SK_WHITELIST_SERIALIZED_TYPEFACES
24 extern void WhitelistSerializeTypeface(const SkTypeface*, SkWStream* );
25 #define SK_TYPEFACE_DELEGATE WhitelistSerializeTypeface
26 #else
27 #define SK_TYPEFACE_DELEGATE nullptr
28 #endif
29 
30 SkTypeface* (*gCreateTypefaceDelegate)(const char [], SkTypeface::Style ) = nullptr;
31 void (*gSerializeTypefaceDelegate)(const SkTypeface*, SkWStream* ) = SK_TYPEFACE_DELEGATE;
32 SkTypeface* (*gDeserializeTypefaceDelegate)(SkStream* ) = nullptr;
33 
34 ///////////////////////////////////////////////////////////////////////////////
35 
36 class SkEmptyTypeface : public SkTypeface {
37 public:
Create()38     static SkEmptyTypeface* Create() { return new SkEmptyTypeface; }
39 protected:
SkEmptyTypeface()40     SkEmptyTypeface() : SkTypeface(SkFontStyle(), 0, true) { }
41 
onOpenStream(int * ttcIndex) const42     SkStreamAsset* onOpenStream(int* ttcIndex) const override { return nullptr; }
onCreateScalerContext(const SkDescriptor *) const43     SkScalerContext* onCreateScalerContext(const SkDescriptor*) const override {
44         return nullptr;
45     }
onFilterRec(SkScalerContextRec *) const46     void onFilterRec(SkScalerContextRec*) const override { }
onGetAdvancedTypefaceMetrics(PerGlyphInfo,const uint32_t *,uint32_t) const47     virtual SkAdvancedTypefaceMetrics* onGetAdvancedTypefaceMetrics(
48                                 PerGlyphInfo,
49                                 const uint32_t*, uint32_t) const override { return nullptr; }
onGetFontDescriptor(SkFontDescriptor *,bool *) const50     void onGetFontDescriptor(SkFontDescriptor*, bool*) const override { }
onCharsToGlyphs(const void * chars,Encoding encoding,uint16_t glyphs[],int glyphCount) const51     virtual int onCharsToGlyphs(const void* chars, Encoding encoding,
52                                 uint16_t glyphs[], int glyphCount) const override {
53         if (glyphs && glyphCount > 0) {
54             sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
55         }
56         return 0;
57     }
onCountGlyphs() const58     int onCountGlyphs() const override { return 0; };
onGetUPEM() const59     int onGetUPEM() const override { return 0; };
60     class EmptyLocalizedStrings : public SkTypeface::LocalizedStrings {
61     public:
next(SkTypeface::LocalizedString *)62         bool next(SkTypeface::LocalizedString*) override { return false; }
63     };
onGetFamilyName(SkString * familyName) const64     void onGetFamilyName(SkString* familyName) const override {
65         familyName->reset();
66     }
onCreateFamilyNameIterator() const67     SkTypeface::LocalizedStrings* onCreateFamilyNameIterator() const override {
68         return new EmptyLocalizedStrings;
69     };
onGetTableTags(SkFontTableTag tags[]) const70     int onGetTableTags(SkFontTableTag tags[]) const override { return 0; }
onGetTableData(SkFontTableTag,size_t,size_t,void *) const71     size_t onGetTableData(SkFontTableTag, size_t, size_t, void*) const override {
72         return 0;
73     }
74 };
75 
76 SK_DECLARE_STATIC_MUTEX(gCreateDefaultMutex);
77 SK_DECLARE_STATIC_ONCE_PTR(SkTypeface, defaults[4]);
78 
GetDefaultTypeface(Style style)79 SkTypeface* SkTypeface::GetDefaultTypeface(Style style) {
80     SkASSERT((int)style < 4);
81     return defaults[style].get([=]{
82         // It is not safe to call FontConfigTypeface::LegacyCreateTypeface concurrently.
83         // To be safe, we serialize here with a mutex so only one call to
84         // CreateTypeface is happening at any given time.
85         // TODO(bungeman, mtklein): This is sad.  Make our fontconfig code safe?
86         SkAutoMutexAcquire lock(&gCreateDefaultMutex);
87 
88         SkAutoTUnref<SkFontMgr> fm(SkFontMgr::RefDefault());
89         SkTypeface* t = fm->legacyCreateTypeface(nullptr, style);
90         return t ? t : SkEmptyTypeface::Create();
91     });
92 }
93 
RefDefault(Style style)94 SkTypeface* SkTypeface::RefDefault(Style style) {
95     return SkRef(GetDefaultTypeface(style));
96 }
97 
UniqueID(const SkTypeface * face)98 uint32_t SkTypeface::UniqueID(const SkTypeface* face) {
99     if (nullptr == face) {
100         face = GetDefaultTypeface();
101     }
102     return face->uniqueID();
103 }
104 
Equal(const SkTypeface * facea,const SkTypeface * faceb)105 bool SkTypeface::Equal(const SkTypeface* facea, const SkTypeface* faceb) {
106     return facea == faceb || SkTypeface::UniqueID(facea) == SkTypeface::UniqueID(faceb);
107 }
108 
109 ///////////////////////////////////////////////////////////////////////////////
110 
CreateFromName(const char name[],Style style)111 SkTypeface* SkTypeface::CreateFromName(const char name[], Style style) {
112     if (gCreateTypefaceDelegate) {
113         SkTypeface* result = (*gCreateTypefaceDelegate)(name, style);
114         if (result) {
115             return result;
116         }
117     }
118     if (nullptr == name) {
119         return RefDefault(style);
120     }
121     SkAutoTUnref<SkFontMgr> fm(SkFontMgr::RefDefault());
122     return fm->legacyCreateTypeface(name, style);
123 }
124 
CreateFromTypeface(const SkTypeface * family,Style s)125 SkTypeface* SkTypeface::CreateFromTypeface(const SkTypeface* family, Style s) {
126     if (!family) {
127         return SkTypeface::RefDefault(s);
128     }
129 
130     if (family->style() == s) {
131         family->ref();
132         return const_cast<SkTypeface*>(family);
133     }
134 
135     SkAutoTUnref<SkFontMgr> fm(SkFontMgr::RefDefault());
136     bool bold = s & SkTypeface::kBold;
137     bool italic = s & SkTypeface::kItalic;
138     SkFontStyle newStyle = SkFontStyle(bold ? SkFontStyle::kBold_Weight
139                                             : SkFontStyle::kNormal_Weight,
140                                        SkFontStyle::kNormal_Width,
141                                        italic ? SkFontStyle::kItalic_Slant
142                                               : SkFontStyle::kUpright_Slant);
143     return fm->matchFaceStyle(family, newStyle);
144 }
145 
CreateFromStream(SkStreamAsset * stream,int index)146 SkTypeface* SkTypeface::CreateFromStream(SkStreamAsset* stream, int index) {
147     SkAutoTUnref<SkFontMgr> fm(SkFontMgr::RefDefault());
148     return fm->createFromStream(stream, index);
149 }
150 
CreateFromFontData(SkFontData * data)151 SkTypeface* SkTypeface::CreateFromFontData(SkFontData* data) {
152     SkAutoTUnref<SkFontMgr> fm(SkFontMgr::RefDefault());
153     return fm->createFromFontData(data);
154 }
155 
CreateFromFile(const char path[],int index)156 SkTypeface* SkTypeface::CreateFromFile(const char path[], int index) {
157     SkAutoTUnref<SkFontMgr> fm(SkFontMgr::RefDefault());
158     return fm->createFromFile(path, index);
159 }
160 
161 ///////////////////////////////////////////////////////////////////////////////
162 
serialize(SkWStream * wstream) const163 void SkTypeface::serialize(SkWStream* wstream) const {
164     if (gSerializeTypefaceDelegate) {
165         (*gSerializeTypefaceDelegate)(this, wstream);
166         return;
167     }
168     bool isLocal = false;
169     SkFontDescriptor desc(this->style());
170     this->onGetFontDescriptor(&desc, &isLocal);
171 
172     // Embed font data if it's a local font.
173     if (isLocal && !desc.hasFontData()) {
174         desc.setFontData(this->onCreateFontData());
175     }
176     desc.serialize(wstream);
177 }
178 
Deserialize(SkStream * stream)179 SkTypeface* SkTypeface::Deserialize(SkStream* stream) {
180     if (gDeserializeTypefaceDelegate) {
181         return (*gDeserializeTypefaceDelegate)(stream);
182     }
183 
184     SkFontDescriptor desc;
185     if (!SkFontDescriptor::Deserialize(stream, &desc)) {
186         return nullptr;
187     }
188 
189     SkFontData* data = desc.detachFontData();
190     if (data) {
191         SkTypeface* typeface = SkTypeface::CreateFromFontData(data);
192         if (typeface) {
193             return typeface;
194         }
195     }
196     return SkTypeface::CreateFromName(desc.getFamilyName(), desc.getStyle());
197 }
198 
199 ///////////////////////////////////////////////////////////////////////////////
200 
countTables() const201 int SkTypeface::countTables() const {
202     return this->onGetTableTags(nullptr);
203 }
204 
getTableTags(SkFontTableTag tags[]) const205 int SkTypeface::getTableTags(SkFontTableTag tags[]) const {
206     return this->onGetTableTags(tags);
207 }
208 
getTableSize(SkFontTableTag tag) const209 size_t SkTypeface::getTableSize(SkFontTableTag tag) const {
210     return this->onGetTableData(tag, 0, ~0U, nullptr);
211 }
212 
getTableData(SkFontTableTag tag,size_t offset,size_t length,void * data) const213 size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length,
214                                 void* data) const {
215     return this->onGetTableData(tag, offset, length, data);
216 }
217 
openStream(int * ttcIndex) const218 SkStreamAsset* SkTypeface::openStream(int* ttcIndex) const {
219     int ttcIndexStorage;
220     if (nullptr == ttcIndex) {
221         // So our subclasses don't need to check for null param
222         ttcIndex = &ttcIndexStorage;
223     }
224     return this->onOpenStream(ttcIndex);
225 }
226 
createFontData() const227 SkFontData* SkTypeface::createFontData() const {
228     return this->onCreateFontData();
229 }
230 
231 // This implementation is temporary until this method can be made pure virtual.
onCreateFontData() const232 SkFontData* SkTypeface::onCreateFontData() const {
233     int index;
234     SkAutoTDelete<SkStreamAsset> stream(this->onOpenStream(&index));
235     return new SkFontData(stream.detach(), index, nullptr, 0);
236 };
237 
charsToGlyphs(const void * chars,Encoding encoding,uint16_t glyphs[],int glyphCount) const238 int SkTypeface::charsToGlyphs(const void* chars, Encoding encoding,
239                               uint16_t glyphs[], int glyphCount) const {
240     if (glyphCount <= 0) {
241         return 0;
242     }
243     if (nullptr == chars || (unsigned)encoding > kUTF32_Encoding) {
244         if (glyphs) {
245             sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
246         }
247         return 0;
248     }
249     return this->onCharsToGlyphs(chars, encoding, glyphs, glyphCount);
250 }
251 
countGlyphs() const252 int SkTypeface::countGlyphs() const {
253     return this->onCountGlyphs();
254 }
255 
getUnitsPerEm() const256 int SkTypeface::getUnitsPerEm() const {
257     // should we try to cache this in the base-class?
258     return this->onGetUPEM();
259 }
260 
getKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const261 bool SkTypeface::getKerningPairAdjustments(const uint16_t glyphs[], int count,
262                                            int32_t adjustments[]) const {
263     SkASSERT(count >= 0);
264     // check for the only legal way to pass a nullptr.. everything is 0
265     // in which case they just want to know if this face can possibly support
266     // kerning (true) or never (false).
267     if (nullptr == glyphs || nullptr == adjustments) {
268         SkASSERT(nullptr == glyphs);
269         SkASSERT(0 == count);
270         SkASSERT(nullptr == adjustments);
271     }
272     return this->onGetKerningPairAdjustments(glyphs, count, adjustments);
273 }
274 
createFamilyNameIterator() const275 SkTypeface::LocalizedStrings* SkTypeface::createFamilyNameIterator() const {
276     return this->onCreateFamilyNameIterator();
277 }
278 
getFamilyName(SkString * name) const279 void SkTypeface::getFamilyName(SkString* name) const {
280     SkASSERT(name);
281     this->onGetFamilyName(name);
282 }
283 
getAdvancedTypefaceMetrics(PerGlyphInfo info,const uint32_t * glyphIDs,uint32_t glyphIDsCount) const284 SkAdvancedTypefaceMetrics* SkTypeface::getAdvancedTypefaceMetrics(
285                                 PerGlyphInfo info,
286                                 const uint32_t* glyphIDs,
287                                 uint32_t glyphIDsCount) const {
288     SkAdvancedTypefaceMetrics* result =
289             this->onGetAdvancedTypefaceMetrics(info, glyphIDs, glyphIDsCount);
290     if (result && result->fType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
291         struct SkOTTableOS2 os2table;
292         if (this->getTableData(SkTEndian_SwapBE32(SkOTTableOS2::TAG), 0,
293                                sizeof(os2table), &os2table) > 0) {
294             if (os2table.version.v2.fsType.field.Bitmap ||
295                 (os2table.version.v2.fsType.field.Restricted &&
296                  !(os2table.version.v2.fsType.field.PreviewPrint ||
297                    os2table.version.v2.fsType.field.Editable))) {
298                 result->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
299                         result->fFlags,
300                         SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag);
301             }
302             if (os2table.version.v2.fsType.field.NoSubsetting) {
303                 result->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
304                         result->fFlags,
305                         SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag);
306             }
307         }
308     }
309     return result;
310 }
311 
onGetKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const312 bool SkTypeface::onGetKerningPairAdjustments(const uint16_t glyphs[], int count,
313                                              int32_t adjustments[]) const {
314     return false;
315 }
316 
317 ///////////////////////////////////////////////////////////////////////////////
318 
319 #include "SkDescriptor.h"
320 #include "SkPaint.h"
321 
getBounds() const322 SkRect SkTypeface::getBounds() const {
323     return *fLazyBounds.get([&] {
324         SkRect* rect = new SkRect;
325         if (!this->onComputeBounds(rect)) {
326             rect->setEmpty();
327         }
328         return rect;
329     });
330 }
331 
onComputeBounds(SkRect * bounds) const332 bool SkTypeface::onComputeBounds(SkRect* bounds) const {
333     // we use a big size to ensure lots of significant bits from the scalercontext.
334     // then we scale back down to return our final answer (at 1-pt)
335     const SkScalar textSize = 2048;
336     const SkScalar invTextSize = 1 / textSize;
337 
338     SkPaint paint;
339     paint.setTypeface(const_cast<SkTypeface*>(this));
340     paint.setTextSize(textSize);
341     paint.setLinearText(true);
342 
343     SkScalerContext::Rec rec;
344     SkScalerContext::MakeRec(paint, nullptr, nullptr, &rec);
345 
346     SkAutoDescriptor ad(sizeof(rec) + SkDescriptor::ComputeOverhead(1));
347     SkDescriptor*    desc = ad.getDesc();
348     desc->init();
349     desc->addEntry(kRec_SkDescriptorTag, sizeof(rec), &rec);
350 
351     SkAutoTDelete<SkScalerContext> ctx(this->createScalerContext(desc, true));
352     if (ctx.get()) {
353         SkPaint::FontMetrics fm;
354         ctx->getFontMetrics(&fm);
355         bounds->set(fm.fXMin * invTextSize, fm.fTop * invTextSize,
356                     fm.fXMax * invTextSize, fm.fBottom * invTextSize);
357         return true;
358     }
359     return false;
360 }
361 
362