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