SkFontHost_linux.cpp revision 66d831dc74953986fb1eef2e10d5b301213ccd4a
1
2/*
3 * Copyright 2006 The Android Open Source Project
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9
10#include "SkFontHost.h"
11#include "SkFontHost_FreeType_common.h"
12#include "SkFontDescriptor.h"
13#include "SkDescriptor.h"
14#include "SkOSFile.h"
15#include "SkPaint.h"
16#include "SkString.h"
17#include "SkStream.h"
18#include "SkThread.h"
19#include "SkTSearch.h"
20
21#ifndef SK_FONT_FILE_PREFIX
22    #define SK_FONT_FILE_PREFIX "/usr/share/fonts/truetype/"
23#endif
24#ifndef SK_FONT_FILE_DIR_SEPERATOR
25    #define SK_FONT_FILE_DIR_SEPERATOR "/"
26#endif
27
28bool find_name_and_attributes(SkStream* stream, SkString* name,
29                              SkTypeface::Style* style, bool* isFixedWidth);
30
31///////////////////////////////////////////////////////////////////////////////
32
33struct FamilyRec;
34
35/*  This guy holds a mapping of a name -> family, used for looking up fonts.
36 Since it is stored in a stretchy array that doesn't preserve object
37 semantics, we don't use constructor/destructors, but just have explicit
38 helpers to manage our internal bookkeeping.
39 */
40struct NameFamilyPair {
41    const char* fName;      // we own this
42    FamilyRec*  fFamily;    // we don't own this, we just reference it
43
44    void construct(const char name[], FamilyRec* family)
45    {
46        fName = strdup(name);
47        fFamily = family;   // we don't own this, so just record the referene
48    }
49    void destruct()
50    {
51        free((char*)fName);
52        // we don't own family, so just ignore our reference
53    }
54};
55
56// we use atomic_inc to grow this for each typeface we create
57static int32_t gUniqueFontID;
58
59// this is the mutex that protects these globals
60SK_DECLARE_STATIC_MUTEX(gFamilyMutex);
61static FamilyRec* gFamilyHead;
62static SkTDArray<NameFamilyPair> gNameList;
63
64struct FamilyRec {
65    FamilyRec*  fNext;
66    SkTypeface* fFaces[4];
67
68    FamilyRec()
69    {
70        fNext = gFamilyHead;
71        memset(fFaces, 0, sizeof(fFaces));
72        gFamilyHead = this;
73    }
74};
75
76static SkTypeface* find_best_face(const FamilyRec* family,
77                                  SkTypeface::Style style) {
78    SkTypeface* const* faces = family->fFaces;
79
80    if (faces[style] != NULL) { // exact match
81        return faces[style];
82    }
83    // look for a matching bold
84    style = (SkTypeface::Style)(style ^ SkTypeface::kItalic);
85    if (faces[style] != NULL) {
86        return faces[style];
87    }
88    // look for the plain
89    if (faces[SkTypeface::kNormal] != NULL) {
90        return faces[SkTypeface::kNormal];
91    }
92    // look for anything
93    for (int i = 0; i < 4; i++) {
94        if (faces[i] != NULL) {
95            return faces[i];
96        }
97    }
98    // should never get here, since the faces list should not be empty
99    SkDEBUGFAIL("faces list is empty");
100    return NULL;
101}
102
103static FamilyRec* find_family(const SkTypeface* member) {
104    FamilyRec* curr = gFamilyHead;
105    while (curr != NULL) {
106        for (int i = 0; i < 4; i++) {
107            if (curr->fFaces[i] == member) {
108                return curr;
109            }
110        }
111        curr = curr->fNext;
112    }
113    return NULL;
114}
115
116static SkTypeface* find_from_uniqueID(uint32_t uniqueID) {
117    FamilyRec* curr = gFamilyHead;
118    while (curr != NULL) {
119        for (int i = 0; i < 4; i++) {
120            SkTypeface* face = curr->fFaces[i];
121            if (face != NULL && face->uniqueID() == uniqueID) {
122                return face;
123            }
124        }
125        curr = curr->fNext;
126    }
127    return NULL;
128}
129
130/*  Remove reference to this face from its family. If the resulting family
131 is empty (has no faces), return that family, otherwise return NULL
132 */
133static FamilyRec* remove_from_family(const SkTypeface* face) {
134    FamilyRec* family = find_family(face);
135    SkASSERT(family->fFaces[face->style()] == face);
136    family->fFaces[face->style()] = NULL;
137
138    for (int i = 0; i < 4; i++) {
139        if (family->fFaces[i] != NULL) {    // family is non-empty
140            return NULL;
141        }
142    }
143    return family;  // return the empty family
144}
145
146// maybe we should make FamilyRec be doubly-linked
147static void detach_and_delete_family(FamilyRec* family) {
148    FamilyRec* curr = gFamilyHead;
149    FamilyRec* prev = NULL;
150
151    while (curr != NULL) {
152        FamilyRec* next = curr->fNext;
153        if (curr == family) {
154            if (prev == NULL) {
155                gFamilyHead = next;
156            } else {
157                prev->fNext = next;
158            }
159            SkDELETE(family);
160            return;
161        }
162        prev = curr;
163        curr = next;
164    }
165    SkDEBUGFAIL("Yikes, couldn't find family in our list to remove/delete");
166}
167
168static const char* find_family_name(const SkTypeface* familyMember) {
169    const FamilyRec* familyRec = find_family(familyMember);
170    for (int i = 0; i < gNameList.count(); i++) {
171        if (gNameList[i].fFamily == familyRec) {
172            return gNameList[i].fName;
173        }
174    }
175    return NULL;
176}
177
178static FamilyRec* find_familyrec(const char name[]) {
179    const NameFamilyPair* list = gNameList.begin();
180    int index = SkStrLCSearch(&list[0].fName, gNameList.count(), name,
181                              sizeof(list[0]));
182    return index >= 0 ? list[index].fFamily : NULL;
183}
184
185static SkTypeface* find_typeface(const char name[], SkTypeface::Style style) {
186    FamilyRec* rec = find_familyrec(name);
187    return rec ? find_best_face(rec, style) : NULL;
188}
189
190static SkTypeface* find_typeface(const SkTypeface* familyMember,
191                                 SkTypeface::Style style) {
192    const FamilyRec* family = find_family(familyMember);
193    return family ? find_best_face(family, style) : NULL;
194}
195
196static void add_name(const char name[], FamilyRec* family) {
197    SkAutoAsciiToLC tolc(name);
198    name = tolc.lc();
199
200    NameFamilyPair* list = gNameList.begin();
201    int             count = gNameList.count();
202
203    int index = SkStrLCSearch(&list[0].fName, count, name, sizeof(list[0]));
204
205    if (index < 0) {
206        list = gNameList.insert(~index);
207        list->construct(name, family);
208    }
209}
210
211static void remove_from_names(FamilyRec* emptyFamily) {
212#ifdef SK_DEBUG
213    for (int i = 0; i < 4; i++) {
214        SkASSERT(emptyFamily->fFaces[i] == NULL);
215    }
216#endif
217
218    SkTDArray<NameFamilyPair>& list = gNameList;
219
220    // must go backwards when removing
221    for (int i = list.count() - 1; i >= 0; --i) {
222        NameFamilyPair* pair = &list[i];
223        if (pair->fFamily == emptyFamily) {
224            pair->destruct();
225            list.remove(i);
226        }
227    }
228}
229
230///////////////////////////////////////////////////////////////////////////////
231
232class FamilyTypeface : public SkTypeface_FreeType {
233public:
234    FamilyTypeface(Style style, bool sysFont, FamilyRec* family, bool isFixedWidth)
235    : INHERITED(style, sk_atomic_inc(&gUniqueFontID) + 1, isFixedWidth) {
236        fIsSysFont = sysFont;
237
238        SkAutoMutexAcquire  ac(gFamilyMutex);
239
240        if (NULL == family) {
241            family = SkNEW(FamilyRec);
242        }
243        family->fFaces[style] = this;
244        fFamilyRec = family;    // just record it so we can return it if asked
245    }
246
247    virtual ~FamilyTypeface() {
248        SkAutoMutexAcquire  ac(gFamilyMutex);
249
250        // remove us from our family. If the family is now empty, we return
251        // that and then remove that family from the name list
252        FamilyRec* family = remove_from_family(this);
253        if (NULL != family) {
254            remove_from_names(family);
255            detach_and_delete_family(family);
256        }
257    }
258
259    bool isSysFont() const { return fIsSysFont; }
260    FamilyRec* getFamily() const { return fFamilyRec; }
261    // openStream returns a SkStream that has been ref-ed
262    virtual SkStream* openStream() = 0;
263    virtual const char* getUniqueString() const = 0;
264
265private:
266    FamilyRec*  fFamilyRec; // we don't own this, just point to it
267    bool        fIsSysFont;
268
269    typedef SkTypeface_FreeType INHERITED;
270};
271
272///////////////////////////////////////////////////////////////////////////////
273
274/* This subclass is just a place holder for when we have no fonts available.
275    It exists so that our globals (e.g. gFamilyHead) that expect *something*
276    will not be null.
277 */
278class EmptyTypeface : public FamilyTypeface {
279public:
280    EmptyTypeface() : INHERITED(SkTypeface::kNormal, true, NULL, false) {}
281
282    // overrides
283    virtual SkStream* openStream() SK_OVERRIDE { return NULL; }
284    virtual const char* getUniqueString() SK_OVERRIDE const { return NULL; }
285
286private:
287    typedef FamilyTypeface INHERITED;
288};
289
290class StreamTypeface : public FamilyTypeface {
291public:
292    StreamTypeface(Style style, bool sysFont, FamilyRec* family,
293                   SkStream* stream, bool isFixedWidth)
294    : INHERITED(style, sysFont, family, isFixedWidth) {
295        stream->ref();
296        fStream = stream;
297    }
298    virtual ~StreamTypeface() {
299        fStream->unref();
300    }
301
302    virtual SkStream* openStream() SK_OVERRIDE {
303      // openStream returns a refed stream.
304      fStream->ref();
305      return fStream;
306    }
307    virtual const char* getUniqueString() const SK_OVERRIDE { return NULL; }
308
309private:
310    SkStream* fStream;
311
312    typedef FamilyTypeface INHERITED;
313};
314
315class FileTypeface : public FamilyTypeface {
316public:
317    FileTypeface(Style style, bool sysFont, FamilyRec* family,
318                 const char path[], bool isFixedWidth)
319        : INHERITED(style, sysFont, family, isFixedWidth) {
320        fPath.set(path);
321    }
322
323    virtual SkStream* openStream() SK_OVERRIDE {
324        return SkStream::NewFromFile(fPath.c_str());
325    }
326
327    virtual const char* getUniqueString() const SK_OVERRIDE {
328        const char* str = strrchr(fPath.c_str(), '/');
329        if (str) {
330            str += 1;   // skip the '/'
331        }
332        return str;
333    }
334
335private:
336    SkString fPath;
337
338    typedef FamilyTypeface INHERITED;
339};
340
341///////////////////////////////////////////////////////////////////////////////
342///////////////////////////////////////////////////////////////////////////////
343
344static bool get_name_and_style(const char path[], SkString* name,
345                               SkTypeface::Style* style, bool* isFixedWidth) {
346    SkAutoTUnref<SkStream> stream(SkStream::NewFromFile(path));
347    if (stream.get()) {
348        return find_name_and_attributes(stream, name, style, isFixedWidth);
349    } else {
350        SkDebugf("---- failed to open <%s> as a font\n", path);
351        return false;
352    }
353}
354
355// these globals are assigned (once) by load_system_fonts()
356static SkTypeface* gFallBackTypeface;
357static FamilyRec* gDefaultFamily;
358static SkTypeface* gDefaultNormal;
359
360static void load_directory_fonts(const SkString& directory, unsigned int* count) {
361    SkOSFile::Iter  iter(directory.c_str(), ".ttf");
362    SkString        name;
363
364    while (iter.next(&name, false)) {
365        SkString filename(directory);
366        filename.append(name);
367
368        bool isFixedWidth;
369        SkString realname;
370        SkTypeface::Style style = SkTypeface::kNormal; // avoid uninitialized warning
371
372        if (!get_name_and_style(filename.c_str(), &realname, &style, &isFixedWidth)) {
373            SkDebugf("------ can't load <%s> as a font\n", filename.c_str());
374            continue;
375        }
376
377        FamilyRec* family = find_familyrec(realname.c_str());
378        if (family && family->fFaces[style]) {
379            continue;
380        }
381
382        // this constructor puts us into the global gFamilyHead llist
383        FamilyTypeface* tf = SkNEW_ARGS(FileTypeface,
384                                        (style,
385                                         true,  // system-font (cannot delete)
386                                         family, // what family to join
387                                         filename.c_str(),
388                                         isFixedWidth) // filename
389                                        );
390
391        if (NULL == family) {
392            add_name(realname.c_str(), tf->getFamily());
393        }
394        *count += 1;
395    }
396
397    SkOSFile::Iter  dirIter(directory.c_str());
398    while (dirIter.next(&name, true)) {
399        if (name.startsWith(".")) {
400            continue;
401        }
402        SkString dirname(directory);
403        dirname.append(name);
404        dirname.append(SK_FONT_FILE_DIR_SEPERATOR);
405        load_directory_fonts(dirname, count);
406    }
407}
408
409static void load_system_fonts() {
410    // check if we've already be called
411    if (NULL != gDefaultNormal) {
412        return;
413    }
414
415    SkString baseDirectory(SK_FONT_FILE_PREFIX);
416    unsigned int count = 0;
417    load_directory_fonts(baseDirectory, &count);
418
419    if (0 == count) {
420        SkNEW(EmptyTypeface);
421    }
422
423    // do this after all fonts are loaded. This is our default font, and it
424    // acts as a sentinel so we only execute load_system_fonts() once
425    static const char* gDefaultNames[] = {
426        "Arial", "Verdana", "Times New Roman", NULL
427    };
428    const char** names = gDefaultNames;
429    while (*names) {
430        SkTypeface* tf = find_typeface(*names++, SkTypeface::kNormal);
431        if (tf) {
432            gDefaultNormal = tf;
433            break;
434        }
435    }
436    // check if we found *something*
437    if (NULL == gDefaultNormal) {
438        if (NULL == gFamilyHead) {
439            sk_throw();
440        }
441        for (int i = 0; i < 4; i++) {
442            if ((gDefaultNormal = gFamilyHead->fFaces[i]) != NULL) {
443                break;
444            }
445        }
446    }
447    if (NULL == gDefaultNormal) {
448        sk_throw();
449    }
450    gFallBackTypeface = gDefaultNormal;
451    gDefaultFamily = find_family(gDefaultNormal);
452}
453
454///////////////////////////////////////////////////////////////////////////////
455
456void SkFontHost::Serialize(const SkTypeface* face, SkWStream* stream) {
457
458    SkFontDescriptor descriptor;
459    descriptor.setFamilyName(find_family_name(face));
460    descriptor.setStyle(face->style());
461    descriptor.setFontFileName(((FamilyTypeface*)face)->getUniqueString());
462
463    descriptor.serialize(stream);
464
465    const bool isCustomFont = !((FamilyTypeface*)face)->isSysFont();
466    if (isCustomFont) {
467        // store the entire font in the fontData
468        SkStream* fontStream = ((FamilyTypeface*)face)->openStream();
469        const uint32_t length = fontStream->getLength();
470
471        stream->writePackedUInt(length);
472        stream->writeStream(fontStream, length);
473
474        fontStream->unref();
475    } else {
476        stream->writePackedUInt(0);
477    }
478}
479
480SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
481    load_system_fonts();
482
483    SkFontDescriptor descriptor(stream);
484    const char* familyName = descriptor.getFamilyName();
485    const SkTypeface::Style style = descriptor.getStyle();
486
487    const uint32_t customFontDataLength = stream->readPackedUInt();
488    if (customFontDataLength > 0) {
489
490        // generate a new stream to store the custom typeface
491        SkMemoryStream* fontStream = new SkMemoryStream(customFontDataLength - 1);
492        stream->read((void*)fontStream->getMemoryBase(), customFontDataLength - 1);
493
494        SkTypeface* face = CreateTypefaceFromStream(fontStream);
495
496        fontStream->unref();
497        return face;
498    }
499
500    return SkFontHost::CreateTypeface(NULL, familyName, style);
501}
502
503///////////////////////////////////////////////////////////////////////////////
504
505SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
506                                       const char familyName[],
507                                       SkTypeface::Style style) {
508    load_system_fonts();
509
510    SkAutoMutexAcquire  ac(gFamilyMutex);
511
512    // clip to legal style bits
513    style = (SkTypeface::Style)(style & SkTypeface::kBoldItalic);
514
515    SkTypeface* tf = NULL;
516
517    if (NULL != familyFace) {
518        tf = find_typeface(familyFace, style);
519    } else if (NULL != familyName) {
520        //        SkDebugf("======= familyName <%s>\n", familyName);
521        tf = find_typeface(familyName, style);
522    }
523
524    if (NULL == tf) {
525        tf = find_best_face(gDefaultFamily, style);
526    }
527
528    SkSafeRef(tf);
529    return tf;
530}
531
532SkStream* SkFontHost::OpenStream(uint32_t fontID) {
533    FamilyTypeface* tf = (FamilyTypeface*)find_from_uniqueID(fontID);
534    SkStream* stream = tf ? tf->openStream() : NULL;
535
536    if (stream && stream->getLength() == 0) {
537        stream->unref();
538        stream = NULL;
539    }
540    return stream;
541}
542
543SkTypeface* SkFontHost::NextLogicalTypeface(SkFontID currFontID, SkFontID origFontID) {
544    return NULL;
545}
546
547///////////////////////////////////////////////////////////////////////////////
548
549SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream) {
550    if (NULL == stream || stream->getLength() <= 0) {
551        SkDELETE(stream);
552        return NULL;
553    }
554
555    bool isFixedWidth;
556    SkTypeface::Style style;
557    if (find_name_and_attributes(stream, NULL, &style, &isFixedWidth)) {
558        return SkNEW_ARGS(StreamTypeface, (style, false, NULL, stream, isFixedWidth));
559    } else {
560        return NULL;
561    }
562}
563
564SkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[]) {
565    SkAutoTUnref<SkStream> stream(SkStream::NewFromFile(path));
566    return stream.get() ? CreateTypefaceFromStream(stream) : NULL;
567}
568