FontCollection.cpp revision 89566f0ada1cafe673efa064cde38467990235d4
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// #define VERBOSE_DEBUG
18
19#define LOG_TAG "Minikin"
20#include <cutils/log.h>
21
22#include "MinikinInternal.h"
23#include <minikin/CmapCoverage.h>
24#include <minikin/FontCollection.h>
25
26using std::vector;
27
28namespace android {
29
30template <typename T>
31static inline T max(T a, T b) {
32    return a>b ? a : b;
33}
34
35uint32_t FontCollection::sNextId = 0;
36
37FontCollection::FontCollection(const vector<FontFamily*>& typefaces) :
38    mMaxChar(0) {
39    AutoMutex _l(gMinikinLock);
40    mId = sNextId++;
41    vector<uint32_t> lastChar;
42    size_t nTypefaces = typefaces.size();
43#ifdef VERBOSE_DEBUG
44    ALOGD("nTypefaces = %d\n", nTypefaces);
45#endif
46    const FontStyle defaultStyle;
47    for (size_t i = 0; i < nTypefaces; i++) {
48        FontFamily* family = typefaces[i];
49        family->RefLocked();
50        FontInstance dummy;
51        mInstances.push_back(dummy);  // emplace_back would be better
52        FontInstance* instance = &mInstances.back();
53        instance->mFamily = family;
54        instance->mCoverage = new SparseBitSet;
55        MinikinFont* typeface = family->getClosestMatch(defaultStyle);
56        if (typeface == NULL) {
57            ALOGE("FontCollection: closest match was null");
58            // TODO: we shouldn't hit this, as there should be more robust
59            // checks upstream to prevent empty/invalid FontFamily objects
60            continue;
61        }
62#ifdef VERBOSE_DEBUG
63        ALOGD("closest match = %p, family size = %d\n", typeface, family->getNumFonts());
64#endif
65        const uint32_t cmapTag = MinikinFont::MakeTag('c', 'm', 'a', 'p');
66        size_t cmapSize = 0;
67        bool ok = typeface->GetTable(cmapTag, NULL, &cmapSize);
68        UniquePtr<uint8_t[]> cmapData(new uint8_t[cmapSize]);
69        ok = typeface->GetTable(cmapTag, cmapData.get(), &cmapSize);
70        CmapCoverage::getCoverage(*instance->mCoverage, cmapData.get(), cmapSize);
71#ifdef VERBOSE_DEBUG
72        ALOGD("font coverage length=%d, first ch=%x\n", instance->mCoverage->length(),
73                instance->mCoverage->nextSetBit(0));
74#endif
75        mMaxChar = max(mMaxChar, instance->mCoverage->length());
76        lastChar.push_back(instance->mCoverage->nextSetBit(0));
77    }
78    size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage;
79    size_t offset = 0;
80    for (size_t i = 0; i < nPages; i++) {
81        Range dummy;
82        mRanges.push_back(dummy);
83        Range* range = &mRanges.back();
84#ifdef VERBOSE_DEBUG
85        ALOGD("i=%d: range start = %d\n", i, offset);
86#endif
87        range->start = offset;
88        for (size_t j = 0; j < nTypefaces; j++) {
89            if (lastChar[j] < (i + 1) << kLogCharsPerPage) {
90                const FontInstance* instance = &mInstances[j];
91                mInstanceVec.push_back(instance);
92                offset++;
93                uint32_t nextChar = instance->mCoverage->nextSetBit((i + 1) << kLogCharsPerPage);
94#ifdef VERBOSE_DEBUG
95                ALOGD("nextChar = %d (j = %d)\n", nextChar, j);
96#endif
97                lastChar[j] = nextChar;
98            }
99        }
100        range->end = offset;
101    }
102}
103
104FontCollection::~FontCollection() {
105    for (size_t i = 0; i < mInstances.size(); i++) {
106        delete mInstances[i].mCoverage;
107        mInstances[i].mFamily->UnrefLocked();
108    }
109}
110
111// Implement heuristic for choosing best-match font. Here are the rules:
112// 1. If first font in the collection has the character, it wins.
113// 2. If a font matches both language and script, it gets a score of 4.
114// 3. If a font matches just language, it gets a score of 2.
115// 4. Matching the "compact" or "elegant" variant adds one to the score.
116// 5. Highest score wins, with ties resolved to the first font.
117const FontCollection::FontInstance* FontCollection::getInstanceForChar(uint32_t ch,
118            FontLanguage lang, int variant) const {
119    if (ch >= mMaxChar) {
120        return NULL;
121    }
122    const Range& range = mRanges[ch >> kLogCharsPerPage];
123#ifdef VERBOSE_DEBUG
124    ALOGD("querying range %d:%d\n", range.start, range.end);
125#endif
126    const FontInstance* bestInstance = NULL;
127    int bestScore = -1;
128    for (size_t i = range.start; i < range.end; i++) {
129        const FontInstance* instance = mInstanceVec[i];
130        if (instance->mCoverage->get(ch)) {
131            FontFamily* family = instance->mFamily;
132            // First font family in collection always matches
133            if (mInstances[0].mFamily == family) {
134                return instance;
135            }
136            int score = lang.match(family->lang()) * 2;
137            if (variant != 0 && variant == family->variant()) {
138                score++;
139            }
140            if (score > bestScore) {
141                bestScore = score;
142                bestInstance = instance;
143            }
144        }
145    }
146    return bestInstance;
147}
148
149void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
150        vector<Run>* result) const {
151    FontLanguage lang = style.getLanguage();
152    int variant = style.getVariant();
153    const FontInstance* lastInstance = NULL;
154    Run* run = NULL;
155    int nShorts;
156    for (size_t i = 0; i < string_size; i += nShorts) {
157        nShorts = 1;
158        uint32_t ch = string[i];
159        // sigh, decode UTF-16 by hand here
160        if ((ch & 0xfc00) == 0xd800) {
161            if ((i + 1) < string_size) {
162                ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff);
163                nShorts = 2;
164            }
165        }
166        // Continue using existing font as long as it has coverage.
167        if (lastInstance == NULL || !lastInstance->mCoverage->get(ch)) {
168            const FontInstance* instance = getInstanceForChar(ch, lang, variant);
169            if (i == 0 || instance != lastInstance) {
170                Run dummy;
171                result->push_back(dummy);
172                run = &result->back();
173                if (instance == NULL) {
174                    run->font = NULL;  // maybe we should do something different here
175                } else {
176                    run->font = instance->mFamily->getClosestMatch(style);
177                    // TODO: simplify refcounting (FontCollection lifetime dominates)
178                    run->font->RefLocked();
179                }
180                lastInstance = instance;
181                run->start = i;
182            }
183        }
184        run->end = i + nShorts;
185    }
186}
187
188MinikinFont* FontCollection::baseFont(FontStyle style) {
189    if (mInstances.empty()) {
190        return NULL;
191    }
192    return mInstances[0].mFamily->getClosestMatch(style);
193}
194
195
196uint32_t FontCollection::getId() const {
197    return mId;
198}
199
200}  // namespace android
201