SkFontHost_linux.cpp revision a8e2e1504b9af6ba791637f228debaa23953064a
1/*
2 * Copyright 2006 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 "SkFontHost.h"
9#include "SkFontHost_FreeType_common.h"
10#include "SkFontDescriptor.h"
11#include "SkFontMgr.h"
12#include "SkDescriptor.h"
13#include "SkOSFile.h"
14#include "SkPaint.h"
15#include "SkString.h"
16#include "SkStream.h"
17#include "SkThread.h"
18#include "SkTSearch.h"
19#include "SkTypefaceCache.h"
20#include "SkTArray.h"
21
22#include <limits>
23
24#ifndef SK_FONT_FILE_PREFIX
25#    define SK_FONT_FILE_PREFIX "/usr/share/fonts/truetype/"
26#endif
27
28///////////////////////////////////////////////////////////////////////////////
29
30/** The base SkTypeface implementation for the custom font manager. */
31class SkTypeface_Custom : public SkTypeface_FreeType {
32public:
33    SkTypeface_Custom(Style style, bool isFixedPitch, bool sysFont, const SkString familyName)
34        : INHERITED(style, SkTypefaceCache::NewFontID(), isFixedPitch)
35        , fIsSysFont(sysFont), fFamilyName(familyName)
36    { }
37
38    bool isSysFont() const { return fIsSysFont; }
39
40    virtual const char* getUniqueString() const = 0;
41
42protected:
43    virtual void onGetFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const SK_OVERRIDE {
44        desc->setFamilyName(fFamilyName.c_str());
45        desc->setFontFileName(this->getUniqueString());
46        *isLocal = !this->isSysFont();
47    }
48
49private:
50    bool fIsSysFont;
51    SkString fFamilyName;
52
53    typedef SkTypeface_FreeType INHERITED;
54};
55
56/** The empty SkTypeface implementation for the custom font manager.
57 *  Used as the last resort fallback typeface.
58 */
59class SkTypeface_Empty : public SkTypeface_Custom {
60public:
61    SkTypeface_Empty() : INHERITED(SkTypeface::kNormal, false, true, SkString()) {}
62
63    virtual const char* getUniqueString() const SK_OVERRIDE { return NULL; }
64
65protected:
66    virtual SkStream* onOpenStream(int*) const SK_OVERRIDE { return NULL; }
67
68private:
69    typedef SkTypeface_Custom INHERITED;
70};
71
72/** The stream SkTypeface implementation for the custom font manager. */
73class SkTypeface_Stream : public SkTypeface_Custom {
74public:
75    SkTypeface_Stream(Style style, bool isFixedPitch, bool sysFont, const SkString familyName,
76                      SkStream* stream, int ttcIndex)
77        : INHERITED(style, isFixedPitch, sysFont, familyName)
78        , fStream(SkRef(stream)), fTtcIndex(ttcIndex)
79    { }
80
81    virtual const char* getUniqueString() const SK_OVERRIDE { return NULL; }
82
83protected:
84    virtual SkStream* onOpenStream(int* ttcIndex) const SK_OVERRIDE {
85        *ttcIndex = 0;
86        return fStream->duplicate();
87    }
88
89private:
90    SkAutoTUnref<SkStream> fStream;
91    int fTtcIndex;
92
93    typedef SkTypeface_Custom INHERITED;
94};
95
96/** The file SkTypeface implementation for the custom font manager. */
97class SkTypeface_File : public SkTypeface_Custom {
98public:
99    SkTypeface_File(Style style, bool isFixedPitch, bool sysFont, const SkString familyName,
100                    const char path[])
101        : INHERITED(style, isFixedPitch, sysFont, familyName)
102        , fPath(path)
103    { }
104
105    virtual const char* getUniqueString() const SK_OVERRIDE {
106        const char* str = strrchr(fPath.c_str(), '/');
107        if (str) {
108            str += 1;   // skip the '/'
109        }
110        return str;
111    }
112
113protected:
114    virtual SkStream* onOpenStream(int* ttcIndex) const SK_OVERRIDE {
115        *ttcIndex = 0;
116        return SkStream::NewFromFile(fPath.c_str());
117    }
118
119private:
120    SkString fPath;
121
122    typedef SkTypeface_Custom INHERITED;
123};
124
125///////////////////////////////////////////////////////////////////////////////
126
127/**
128 *  SkFontStyleSet_Custom
129 *
130 *  This class is used by SkFontMgr_Custom to hold SkTypeface_Custom families.
131 */
132class SkFontStyleSet_Custom : public SkFontStyleSet {
133public:
134    explicit SkFontStyleSet_Custom(const SkString familyName) : fFamilyName(familyName) { }
135
136    virtual int count() SK_OVERRIDE {
137        return fStyles.count();
138    }
139
140    virtual void getStyle(int index, SkFontStyle* style, SkString* name) SK_OVERRIDE {
141        SkASSERT(index < fStyles.count());
142        bool bold = fStyles[index]->isBold();
143        bool italic = fStyles[index]->isItalic();
144        *style = SkFontStyle(bold ? SkFontStyle::kBold_Weight : SkFontStyle::kNormal_Weight,
145                             SkFontStyle::kNormal_Width,
146                             italic ? SkFontStyle::kItalic_Slant : SkFontStyle::kUpright_Slant);
147        name->reset();
148    }
149
150    virtual SkTypeface* createTypeface(int index) SK_OVERRIDE {
151        SkASSERT(index < fStyles.count());
152        return SkRef(fStyles[index].get());
153    }
154
155    static int match_score(const SkFontStyle& pattern, const SkFontStyle& candidate) {
156        int score = 0;
157        score += (pattern.width() - candidate.width()) * 100;
158        score += (pattern.isItalic() == candidate.isItalic()) ? 0 : 1000;
159        score += pattern.weight() - candidate.weight();
160        return score;
161    }
162
163    virtual SkTypeface* matchStyle(const SkFontStyle& pattern) SK_OVERRIDE {
164        if (0 == fStyles.count()) {
165            return NULL;
166        }
167
168        SkTypeface_Custom* closest = fStyles[0];
169        int minScore = std::numeric_limits<int>::max();
170        for (int i = 0; i < fStyles.count(); ++i) {
171            bool bold = fStyles[i]->isBold();
172            bool italic = fStyles[i]->isItalic();
173            SkFontStyle style = SkFontStyle(bold ? SkFontStyle::kBold_Weight
174                                                 : SkFontStyle::kNormal_Weight,
175                                            SkFontStyle::kNormal_Width,
176                                            italic ? SkFontStyle::kItalic_Slant
177                                                   : SkFontStyle::kUpright_Slant);
178
179            int score = match_score(pattern, style);
180            if (score < minScore) {
181                closest = fStyles[i];
182                minScore = score;
183            }
184        }
185        return SkRef(closest);
186    }
187
188private:
189    SkTArray<SkAutoTUnref<SkTypeface_Custom>, true> fStyles;
190    SkString fFamilyName;
191
192    void appendTypeface(SkTypeface_Custom* typeface) {
193        fStyles.push_back().reset(typeface);
194    }
195
196    friend class SkFontMgr_Custom;
197};
198
199/**
200 *  SkFontMgr_Custom
201 *
202 *  This class is essentially a collection of SkFontStyleSet_Custom,
203 *  one SkFontStyleSet_Custom for each family. This class may be modified
204 *  to load fonts from any source by changing the initialization.
205 */
206class SkFontMgr_Custom : public SkFontMgr {
207public:
208    explicit SkFontMgr_Custom(const char* dir) {
209        this->load_system_fonts(dir);
210    }
211
212protected:
213    virtual int onCountFamilies() const SK_OVERRIDE {
214        return fFamilies.count();
215    }
216
217    virtual void onGetFamilyName(int index, SkString* familyName) const SK_OVERRIDE {
218        SkASSERT(index < fFamilies.count());
219        familyName->set(fFamilies[index]->fFamilyName);
220    }
221
222    virtual SkFontStyleSet_Custom* onCreateStyleSet(int index) const SK_OVERRIDE {
223        SkASSERT(index < fFamilies.count());
224        return SkRef(fFamilies[index].get());
225    }
226
227    virtual SkFontStyleSet_Custom* onMatchFamily(const char familyName[]) const SK_OVERRIDE {
228        for (int i = 0; i < fFamilies.count(); ++i) {
229            if (fFamilies[i]->fFamilyName.equals(familyName)) {
230                return SkRef(fFamilies[i].get());
231            }
232        }
233        return NULL;
234    }
235
236    virtual SkTypeface* onMatchFamilyStyle(const char familyName[],
237                                           const SkFontStyle& fontStyle) const SK_OVERRIDE
238    {
239        SkAutoTUnref<SkFontStyleSet> sset(this->matchFamily(familyName));
240        return sset->matchStyle(fontStyle);
241    }
242
243    virtual SkTypeface* onMatchFaceStyle(const SkTypeface* familyMember,
244                                         const SkFontStyle& fontStyle) const SK_OVERRIDE
245    {
246        for (int i = 0; i < fFamilies.count(); ++i) {
247            for (int j = 0; j < fFamilies[i]->fStyles.count(); ++j) {
248                if (fFamilies[i]->fStyles[j] == familyMember) {
249                    return fFamilies[i]->matchStyle(fontStyle);
250                }
251            }
252        }
253        return NULL;
254    }
255
256    virtual SkTypeface* onCreateFromData(SkData* data, int ttcIndex) const SK_OVERRIDE {
257        SkAutoTUnref<SkStream> stream(new SkMemoryStream(data));
258        return this->createFromStream(stream, ttcIndex);
259    }
260
261    virtual SkTypeface* onCreateFromStream(SkStream* stream, int ttcIndex) const SK_OVERRIDE {
262        if (NULL == stream || stream->getLength() <= 0) {
263            SkDELETE(stream);
264            return NULL;
265        }
266
267        bool isFixedPitch;
268        SkTypeface::Style style;
269        SkString name;
270        if (SkTypeface_FreeType::ScanFont(stream, ttcIndex, &name, &style, &isFixedPitch)) {
271            return SkNEW_ARGS(SkTypeface_Stream, (style, isFixedPitch, false, name,
272                                                  stream, ttcIndex));
273        } else {
274            return NULL;
275        }
276    }
277
278    virtual SkTypeface* onCreateFromFile(const char path[], int ttcIndex) const SK_OVERRIDE {
279        SkAutoTUnref<SkStream> stream(SkStream::NewFromFile(path));
280        return stream.get() ? this->createFromStream(stream, ttcIndex) : NULL;
281    }
282
283    virtual SkTypeface* onLegacyCreateTypeface(const char familyName[],
284                                               unsigned styleBits) const SK_OVERRIDE
285    {
286        SkTypeface::Style oldStyle = (SkTypeface::Style)styleBits;
287        SkFontStyle style = SkFontStyle(oldStyle & SkTypeface::kBold
288                                                 ? SkFontStyle::kBold_Weight
289                                                 : SkFontStyle::kNormal_Weight,
290                                        SkFontStyle::kNormal_Width,
291                                        oldStyle & SkTypeface::kItalic
292                                                 ? SkFontStyle::kItalic_Slant
293                                                 : SkFontStyle::kUpright_Slant);
294        SkTypeface* tf = NULL;
295
296        if (NULL != familyName) {
297            tf = this->onMatchFamilyStyle(familyName, style);
298        }
299
300        if (NULL == tf) {
301            tf = gDefaultFamily->matchStyle(style);
302        }
303
304        return SkSafeRef(tf);
305    }
306
307private:
308
309    static bool get_name_and_style(const char path[], SkString* name,
310                                   SkTypeface::Style* style, bool* isFixedPitch) {
311        SkAutoTUnref<SkStream> stream(SkStream::NewFromFile(path));
312        if (stream.get()) {
313            return SkTypeface_FreeType::ScanFont(stream, 0, name, style, isFixedPitch);
314        } else {
315            SkDebugf("---- failed to open <%s> as a font\n", path);
316            return false;
317        }
318    }
319
320    void load_directory_fonts(const SkString& directory) {
321        SkOSFile::Iter iter(directory.c_str(), ".ttf");
322        SkString name;
323
324        while (iter.next(&name, false)) {
325            SkString filename(
326                SkOSPath::Join(directory.c_str(), name.c_str()));
327
328            bool isFixedPitch;
329            SkString realname;
330            SkTypeface::Style style = SkTypeface::kNormal; // avoid uninitialized warning
331
332            if (!get_name_and_style(filename.c_str(), &realname, &style, &isFixedPitch)) {
333                SkDebugf("------ can't load <%s> as a font\n", filename.c_str());
334                continue;
335            }
336
337            SkTypeface_Custom* tf = SkNEW_ARGS(SkTypeface_File, (
338                                                style,
339                                                isFixedPitch,
340                                                true,  // system-font (cannot delete)
341                                                realname,
342                                                filename.c_str()));
343
344            SkFontStyleSet_Custom* addTo = this->onMatchFamily(realname.c_str());
345            if (NULL == addTo) {
346                addTo = new SkFontStyleSet_Custom(realname);
347                fFamilies.push_back().reset(addTo);
348            }
349            addTo->appendTypeface(tf);
350        }
351
352        SkOSFile::Iter dirIter(directory.c_str());
353        while (dirIter.next(&name, true)) {
354            if (name.startsWith(".")) {
355                continue;
356            }
357            SkString dirname(SkOSPath::Join(directory.c_str(), name.c_str()));
358            load_directory_fonts(dirname);
359        }
360    }
361
362    void load_system_fonts(const char* dir) {
363        SkString baseDirectory(dir);
364        load_directory_fonts(baseDirectory);
365
366        if (fFamilies.empty()) {
367            SkFontStyleSet_Custom* family = new SkFontStyleSet_Custom(SkString());
368            fFamilies.push_back().reset(family);
369            family->appendTypeface(SkNEW(SkTypeface_Empty));
370        }
371
372        // Try to pick a default font.
373        static const char* gDefaultNames[] = {
374            "Arial", "Verdana", "Times New Roman", "Droid Sans", NULL
375        };
376        for (size_t i = 0; i < SK_ARRAY_COUNT(gDefaultNames); ++i) {
377            SkFontStyleSet_Custom* set = this->onMatchFamily(gDefaultNames[i]);
378            if (NULL == set) {
379                continue;
380            }
381
382            SkTypeface* tf = set->matchStyle(SkFontStyle(SkFontStyle::kNormal_Weight,
383                                                         SkFontStyle::kNormal_Width,
384                                                         SkFontStyle::kUpright_Slant));
385            if (NULL == tf) {
386                continue;
387            }
388
389            gDefaultFamily = set;
390            gDefaultNormal = tf;
391            break;
392        }
393        if (NULL == gDefaultNormal) {
394            gDefaultFamily = fFamilies[0];
395            gDefaultNormal = gDefaultFamily->fStyles[0];
396        }
397    }
398
399    SkTArray<SkAutoTUnref<SkFontStyleSet_Custom>, true> fFamilies;
400    SkFontStyleSet_Custom* gDefaultFamily;
401    SkTypeface* gDefaultNormal;
402};
403
404SkFontMgr* SkFontMgr::Factory() {
405    return new SkFontMgr_Custom(SK_FONT_FILE_PREFIX);
406}
407