FontCollection.cpp revision bb601b67dd05947f92cc23092bfb8a059c2e3377
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        MinikinFont* typeface = family->getClosestMatch(defaultStyle).font;
50        if (typeface == NULL) {
51            ALOGE("FontCollection: closest match was null");
52            // TODO: we shouldn't hit this, as there should be more robust
53            // checks upstream to prevent empty/invalid FontFamily objects
54            continue;
55        }
56        family->RefLocked();
57        FontInstance dummy;
58        mInstances.push_back(dummy);  // emplace_back would be better
59        FontInstance* instance = &mInstances.back();
60        instance->mFamily = family;
61        instance->mCoverage = new SparseBitSet;
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    nTypefaces = mInstances.size();
79    size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage;
80    size_t offset = 0;
81    for (size_t i = 0; i < nPages; i++) {
82        Range dummy;
83        mRanges.push_back(dummy);
84        Range* range = &mRanges.back();
85#ifdef VERBOSE_DEBUG
86        ALOGD("i=%d: range start = %d\n", i, offset);
87#endif
88        range->start = offset;
89        for (size_t j = 0; j < nTypefaces; j++) {
90            if (lastChar[j] < (i + 1) << kLogCharsPerPage) {
91                const FontInstance* instance = &mInstances[j];
92                mInstanceVec.push_back(instance);
93                offset++;
94                uint32_t nextChar = instance->mCoverage->nextSetBit((i + 1) << kLogCharsPerPage);
95#ifdef VERBOSE_DEBUG
96                ALOGD("nextChar = %d (j = %d)\n", nextChar, j);
97#endif
98                lastChar[j] = nextChar;
99            }
100        }
101        range->end = offset;
102    }
103}
104
105FontCollection::~FontCollection() {
106    for (size_t i = 0; i < mInstances.size(); i++) {
107        delete mInstances[i].mCoverage;
108        mInstances[i].mFamily->UnrefLocked();
109    }
110}
111
112// Implement heuristic for choosing best-match font. Here are the rules:
113// 1. If first font in the collection has the character, it wins.
114// 2. If a font matches both language and script, it gets a score of 4.
115// 3. If a font matches just language, it gets a score of 2.
116// 4. Matching the "compact" or "elegant" variant adds one to the score.
117// 5. Highest score wins, with ties resolved to the first font.
118const FontCollection::FontInstance* FontCollection::getInstanceForChar(uint32_t ch,
119            FontLanguage lang, int variant) const {
120    if (ch >= mMaxChar) {
121        return NULL;
122    }
123    const Range& range = mRanges[ch >> kLogCharsPerPage];
124#ifdef VERBOSE_DEBUG
125    ALOGD("querying range %d:%d\n", range.start, range.end);
126#endif
127    const FontInstance* bestInstance = NULL;
128    int bestScore = -1;
129    for (size_t i = range.start; i < range.end; i++) {
130        const FontInstance* instance = mInstanceVec[i];
131        if (instance->mCoverage->get(ch)) {
132            FontFamily* family = instance->mFamily;
133            // First font family in collection always matches
134            if (mInstances[0].mFamily == family) {
135                return instance;
136            }
137            int score = lang.match(family->lang()) * 2;
138            if (variant != 0 && variant == family->variant()) {
139                score++;
140            }
141            if (score > bestScore) {
142                bestScore = score;
143                bestInstance = instance;
144            }
145        }
146    }
147    return bestInstance;
148}
149
150const uint32_t NBSP = 0xa0;
151const uint32_t ZWJ = 0x200c;
152const uint32_t ZWNJ = 0x200d;
153// Characters where we want to continue using existing font run instead of
154// recomputing the best match in the fallback list.
155static const uint32_t stickyWhitelist[] = { '!', ',', '.', ':', ';', '?', NBSP, ZWJ, ZWNJ };
156
157static bool isStickyWhitelisted(uint32_t c) {
158    for (size_t i = 0; i < sizeof(stickyWhitelist) / sizeof(stickyWhitelist[0]); i++) {
159        if (stickyWhitelist[i] == c) return true;
160    }
161    return false;
162}
163
164void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
165        vector<Run>* result) const {
166    FontLanguage lang = style.getLanguage();
167    int variant = style.getVariant();
168    const FontInstance* lastInstance = NULL;
169    Run* run = NULL;
170    int nShorts;
171    for (size_t i = 0; i < string_size; i += nShorts) {
172        nShorts = 1;
173        uint32_t ch = string[i];
174        // sigh, decode UTF-16 by hand here
175        if ((ch & 0xfc00) == 0xd800) {
176            if ((i + 1) < string_size) {
177                ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff);
178                nShorts = 2;
179            }
180        }
181        // Continue using existing font as long as it has coverage and is whitelisted
182        if (lastInstance == NULL
183                || !(isStickyWhitelisted(ch) && lastInstance->mCoverage->get(ch))) {
184            const FontInstance* instance = getInstanceForChar(ch, lang, variant);
185            if (i == 0 || instance != lastInstance) {
186                Run dummy;
187                result->push_back(dummy);
188                run = &result->back();
189                if (instance == NULL) {
190                    run->fakedFont.font = NULL;
191                } else {
192                    run->fakedFont = instance->mFamily->getClosestMatch(style);
193                }
194                lastInstance = instance;
195                run->start = i;
196            }
197        }
198        run->end = i + nShorts;
199    }
200}
201
202MinikinFont* FontCollection::baseFont(FontStyle style) {
203    return baseFontFaked(style).font;
204}
205
206FakedFont FontCollection::baseFontFaked(FontStyle style) {
207    if (mInstances.empty()) {
208        return FakedFont();
209    }
210    return mInstances[0].mFamily->getClosestMatch(style);
211}
212
213uint32_t FontCollection::getId() const {
214    return mId;
215}
216
217}  // namespace android
218