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