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