FontCollection.cpp revision 80d113bcd4bbc395218503354af1a5a6dba59b4b
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 "unicode/unistr.h"
23#include "unicode/unorm2.h"
24
25#include "MinikinInternal.h"
26#include <minikin/FontCollection.h>
27
28using std::vector;
29
30namespace android {
31
32template <typename T>
33static inline T max(T a, T b) {
34    return a>b ? a : b;
35}
36
37uint32_t FontCollection::sNextId = 0;
38
39FontCollection::FontCollection(const vector<FontFamily*>& typefaces) :
40    mMaxChar(0) {
41    AutoMutex _l(gMinikinLock);
42    mId = sNextId++;
43    vector<uint32_t> lastChar;
44    size_t nTypefaces = typefaces.size();
45#ifdef VERBOSE_DEBUG
46    ALOGD("nTypefaces = %zd\n", nTypefaces);
47#endif
48    const FontStyle defaultStyle;
49    for (size_t i = 0; i < nTypefaces; i++) {
50        FontFamily* family = typefaces[i];
51        MinikinFont* typeface = family->getClosestMatch(defaultStyle).font;
52        if (typeface == NULL) {
53            continue;
54        }
55        family->RefLocked();
56        const SparseBitSet* coverage = family->getCoverage();
57        if (coverage == nullptr) {
58            family->UnrefLocked();
59            continue;
60        }
61        mFamilies.push_back(family);  // emplace_back would be better
62        mMaxChar = max(mMaxChar, coverage->length());
63        lastChar.push_back(coverage->nextSetBit(0));
64    }
65    nTypefaces = mFamilies.size();
66    LOG_ALWAYS_FATAL_IF(nTypefaces == 0,
67        "Font collection must have at least one valid typeface");
68    size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage;
69    size_t offset = 0;
70    // TODO: Use variation selector map for mRanges construction.
71    // A font can have a glyph for a base code point and variation selector pair but no glyph for
72    // the base code point without variation selector. The family won't be listed in the range in
73    // this case.
74    for (size_t i = 0; i < nPages; i++) {
75        Range dummy;
76        mRanges.push_back(dummy);
77        Range* range = &mRanges.back();
78#ifdef VERBOSE_DEBUG
79        ALOGD("i=%zd: range start = %zd\n", i, offset);
80#endif
81        range->start = offset;
82        for (size_t j = 0; j < nTypefaces; j++) {
83            if (lastChar[j] < (i + 1) << kLogCharsPerPage) {
84                FontFamily* family = mFamilies[j];
85                mFamilyVec.push_back(family);
86                offset++;
87                uint32_t nextChar = family->getCoverage()->nextSetBit((i + 1) << kLogCharsPerPage);
88#ifdef VERBOSE_DEBUG
89                ALOGD("nextChar = %d (j = %zd)\n", nextChar, j);
90#endif
91                lastChar[j] = nextChar;
92            }
93        }
94        range->end = offset;
95    }
96}
97
98FontCollection::~FontCollection() {
99    for (size_t i = 0; i < mFamilies.size(); i++) {
100        mFamilies[i]->UnrefLocked();
101    }
102}
103
104// Implement heuristic for choosing best-match font. Here are the rules:
105// 1. If first font in the collection has the character, it wins.
106// 2. If a font matches both language and script, it gets a score of 4.
107// 3. If a font matches just language, it gets a score of 2.
108// 4. Matching the "compact" or "elegant" variant adds one to the score.
109// 5. Highest score wins, with ties resolved to the first font.
110FontFamily* FontCollection::getFamilyForChar(uint32_t ch, uint32_t vs,
111            FontLanguage lang, int variant) const {
112    if (ch >= mMaxChar) {
113        return NULL;
114    }
115    const Range& range = mRanges[ch >> kLogCharsPerPage];
116#ifdef VERBOSE_DEBUG
117    ALOGD("querying range %zd:%zd\n", range.start, range.end);
118#endif
119    FontFamily* bestFamily = nullptr;
120    int bestScore = -1;
121    for (size_t i = range.start; i < range.end; i++) {
122        FontFamily* family = mFamilyVec[i];
123        if (vs == 0 ? family->getCoverage()->get(ch) : family->hasVariationSelector(ch, vs)) {
124            // First font family in collection always matches
125            if (mFamilies[0] == family) {
126                return family;
127            }
128            int score = lang.match(family->lang()) * 2;
129            if (family->variant() == 0 || family->variant() == variant) {
130                score++;
131            }
132            if (score > bestScore) {
133                bestScore = score;
134                bestFamily = family;
135            }
136        }
137    }
138    if (bestFamily == nullptr && vs != 0) {
139        // If no fonts support the codepoint and variation selector pair,
140        // fallback to select a font family that supports just the base
141        // character, ignoring the variation selector.
142        return getFamilyForChar(ch, 0, lang, variant);
143    }
144    if (bestFamily == nullptr && !mFamilyVec.empty()) {
145        UErrorCode errorCode = U_ZERO_ERROR;
146        const UNormalizer2* normalizer = unorm2_getNFDInstance(&errorCode);
147        if (U_SUCCESS(errorCode)) {
148            UChar decomposed[4];
149            int len = unorm2_getRawDecomposition(normalizer, ch, decomposed, 4, &errorCode);
150            if (U_SUCCESS(errorCode) && len > 0) {
151                int off = 0;
152                U16_NEXT_UNSAFE(decomposed, off, ch);
153                return getFamilyForChar(ch, vs, lang, variant);
154            }
155        }
156        bestFamily = mFamilies[0];
157    }
158    return bestFamily;
159}
160
161const uint32_t NBSP = 0xa0;
162const uint32_t ZWJ = 0x200c;
163const uint32_t ZWNJ = 0x200d;
164const uint32_t KEYCAP = 0x20e3;
165const uint32_t HYPHEN = 0x2010;
166const uint32_t NB_HYPHEN = 0x2011;
167
168// Characters where we want to continue using existing font run instead of
169// recomputing the best match in the fallback list.
170static const uint32_t stickyWhitelist[] = { '!', ',', '-', '.', ':', ';', '?', NBSP, ZWJ, ZWNJ,
171        KEYCAP, HYPHEN, NB_HYPHEN };
172
173static bool isStickyWhitelisted(uint32_t c) {
174    for (size_t i = 0; i < sizeof(stickyWhitelist) / sizeof(stickyWhitelist[0]); i++) {
175        if (stickyWhitelist[i] == c) return true;
176    }
177    return false;
178}
179
180static bool isVariationSelector(uint32_t c) {
181    return (0xFE00 <= c && c <= 0xFE0F) || (0xE0100 <= c && c <= 0xE01EF);
182}
183
184bool FontCollection::hasVariationSelector(uint32_t baseCodepoint,
185        uint32_t variationSelector) const {
186    if (!isVariationSelector(variationSelector)) {
187        return false;
188    }
189    if (baseCodepoint >= mMaxChar) {
190        return false;
191    }
192    // Currently mRanges can not be used here since it isn't aware of the variation sequence.
193    // TODO: Use mRanges for narrowing down the search range.
194    for (size_t i = 0; i < mFamilies.size(); i++) {
195        if (mFamilies[i]->hasVariationSelector(baseCodepoint, variationSelector)) {
196          return true;
197        }
198    }
199    return false;
200}
201
202void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
203        vector<Run>* result) const {
204    FontLanguage lang = style.getLanguage();
205    int variant = style.getVariant();
206    FontFamily* lastFamily = NULL;
207    Run* run = NULL;
208
209    if (string_size == 0) {
210        return;
211    }
212
213    const uint32_t kEndOfString = 0xFFFFFFFF;
214
215    uint32_t nextCh = 0;
216    uint32_t prevCh = 0;
217    size_t nextUtf16Pos = 0;
218    size_t readLength = 0;
219    U16_NEXT(string, readLength, string_size, nextCh);
220
221    do {
222        const uint32_t ch = nextCh;
223        const size_t utf16Pos = nextUtf16Pos;
224        nextUtf16Pos = readLength;
225        if (readLength < string_size) {
226            U16_NEXT(string, readLength, string_size, nextCh);
227        } else {
228            nextCh = kEndOfString;
229        }
230
231        bool shouldContinueRun = false;
232        if (lastFamily != nullptr) {
233            if (isStickyWhitelisted(ch)) {
234                // Continue using existing font as long as it has coverage and is whitelisted
235                shouldContinueRun = lastFamily->getCoverage()->get(ch);
236            } else if (isVariationSelector(ch)) {
237                // Always continue if the character is a variation selector.
238                shouldContinueRun = true;
239            }
240        }
241
242        if (!shouldContinueRun) {
243            FontFamily* family =
244                    getFamilyForChar(ch, isVariationSelector(nextCh) ? nextCh : 0, lang, variant);
245            if (utf16Pos == 0 || family != lastFamily) {
246                size_t start = utf16Pos;
247                // Workaround for Emoji keycap until we implement per-cluster font
248                // selection: if keycap is found in a different font that also
249                // supports previous char, attach previous char to the new run.
250                // Bug 7557244.
251                if (ch == KEYCAP && utf16Pos != 0 && family && family->getCoverage()->get(prevCh)) {
252                    const size_t prevChLength = U16_LENGTH(prevCh);
253                    run->end -= prevChLength;
254                    if (run->start == run->end) {
255                        result->pop_back();
256                    }
257                    start -= prevChLength;
258                }
259                Run dummy;
260                result->push_back(dummy);
261                run = &result->back();
262                if (family == NULL) {
263                    run->fakedFont.font = NULL;
264                } else {
265                    run->fakedFont = family->getClosestMatch(style);
266                }
267                lastFamily = family;
268                run->start = start;
269            }
270        }
271        prevCh = ch;
272        run->end = nextUtf16Pos;  // exclusive
273    } while (nextCh != kEndOfString);
274}
275
276MinikinFont* FontCollection::baseFont(FontStyle style) {
277    return baseFontFaked(style).font;
278}
279
280FakedFont FontCollection::baseFontFaked(FontStyle style) {
281    if (mFamilies.empty()) {
282        return FakedFont();
283    }
284    return mFamilies[0]->getClosestMatch(style);
285}
286
287uint32_t FontCollection::getId() const {
288    return mId;
289}
290
291void FontCollection::purgeFontFamilyHbFontCache() const {
292    assertMinikinLocked();
293    for (size_t i = 0; i < mFamilies.size(); ++i) {
294        mFamilies[i]->purgeHbFontCache();
295    }
296}
297
298}  // namespace android
299