FontCollection.cpp revision 66a34a04ab34519723f682ef2e71d22405d267c2
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
116    // Even if the font supports variation sequence, mRanges isn't aware of the base character of
117    // the sequence. Search all FontFamilies if variation sequence is specified.
118    // TODO: Always use mRanges for font search.
119    const std::vector<FontFamily*>& familyVec = (vs == 0) ? mFamilyVec : mFamilies;
120    Range range;
121    if (vs == 0) {
122        range = mRanges[ch >> kLogCharsPerPage];
123    } else {
124        range = { 0, mFamilies.size() };
125    }
126
127#ifdef VERBOSE_DEBUG
128    ALOGD("querying range %zd:%zd\n", range.start, range.end);
129#endif
130    FontFamily* bestFamily = nullptr;
131    int bestScore = -1;
132    for (size_t i = range.start; i < range.end; i++) {
133        FontFamily* family = familyVec[i];
134        if (vs == 0 ? family->getCoverage()->get(ch) : family->hasVariationSelector(ch, vs)) {
135            // First font family in collection always matches
136            if (mFamilies[0] == family) {
137                return family;
138            }
139            int score = lang.match(family->lang()) * 2;
140            if (family->variant() == 0 || family->variant() == variant) {
141                score++;
142            }
143            if (score > bestScore) {
144                bestScore = score;
145                bestFamily = family;
146            }
147        }
148    }
149    if (bestFamily == nullptr && vs != 0) {
150        // If no fonts support the codepoint and variation selector pair,
151        // fallback to select a font family that supports just the base
152        // character, ignoring the variation selector.
153        return getFamilyForChar(ch, 0, lang, variant);
154    }
155    if (bestFamily == nullptr && !mFamilyVec.empty()) {
156        UErrorCode errorCode = U_ZERO_ERROR;
157        const UNormalizer2* normalizer = unorm2_getNFDInstance(&errorCode);
158        if (U_SUCCESS(errorCode)) {
159            UChar decomposed[4];
160            int len = unorm2_getRawDecomposition(normalizer, ch, decomposed, 4, &errorCode);
161            if (U_SUCCESS(errorCode) && len > 0) {
162                int off = 0;
163                U16_NEXT_UNSAFE(decomposed, off, ch);
164                return getFamilyForChar(ch, vs, lang, variant);
165            }
166        }
167        bestFamily = mFamilies[0];
168    }
169    return bestFamily;
170}
171
172const uint32_t NBSP = 0xa0;
173const uint32_t ZWJ = 0x200c;
174const uint32_t ZWNJ = 0x200d;
175const uint32_t KEYCAP = 0x20e3;
176const uint32_t HYPHEN = 0x2010;
177const uint32_t NB_HYPHEN = 0x2011;
178
179// Characters where we want to continue using existing font run instead of
180// recomputing the best match in the fallback list.
181static const uint32_t stickyWhitelist[] = { '!', ',', '-', '.', ':', ';', '?', NBSP, ZWJ, ZWNJ,
182        KEYCAP, HYPHEN, NB_HYPHEN };
183
184static bool isStickyWhitelisted(uint32_t c) {
185    for (size_t i = 0; i < sizeof(stickyWhitelist) / sizeof(stickyWhitelist[0]); i++) {
186        if (stickyWhitelist[i] == c) return true;
187    }
188    return false;
189}
190
191static bool isVariationSelector(uint32_t c) {
192    return (0xFE00 <= c && c <= 0xFE0F) || (0xE0100 <= c && c <= 0xE01EF);
193}
194
195bool FontCollection::hasVariationSelector(uint32_t baseCodepoint,
196        uint32_t variationSelector) const {
197    if (!isVariationSelector(variationSelector)) {
198        return false;
199    }
200    if (baseCodepoint >= mMaxChar) {
201        return false;
202    }
203    // Currently mRanges can not be used here since it isn't aware of the variation sequence.
204    // TODO: Use mRanges for narrowing down the search range.
205    for (size_t i = 0; i < mFamilies.size(); i++) {
206        if (mFamilies[i]->hasVariationSelector(baseCodepoint, variationSelector)) {
207          return true;
208        }
209    }
210    return false;
211}
212
213void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
214        vector<Run>* result) const {
215    FontLanguage lang = style.getLanguage();
216    int variant = style.getVariant();
217    FontFamily* lastFamily = NULL;
218    Run* run = NULL;
219
220    if (string_size == 0) {
221        return;
222    }
223
224    const uint32_t kEndOfString = 0xFFFFFFFF;
225
226    uint32_t nextCh = 0;
227    uint32_t prevCh = 0;
228    size_t nextUtf16Pos = 0;
229    size_t readLength = 0;
230    U16_NEXT(string, readLength, string_size, nextCh);
231
232    do {
233        const uint32_t ch = nextCh;
234        const size_t utf16Pos = nextUtf16Pos;
235        nextUtf16Pos = readLength;
236        if (readLength < string_size) {
237            U16_NEXT(string, readLength, string_size, nextCh);
238        } else {
239            nextCh = kEndOfString;
240        }
241
242        bool shouldContinueRun = false;
243        if (lastFamily != nullptr) {
244            if (isStickyWhitelisted(ch)) {
245                // Continue using existing font as long as it has coverage and is whitelisted
246                shouldContinueRun = lastFamily->getCoverage()->get(ch);
247            } else if (isVariationSelector(ch)) {
248                // Always continue if the character is a variation selector.
249                shouldContinueRun = true;
250            }
251        }
252
253        if (!shouldContinueRun) {
254            FontFamily* family =
255                    getFamilyForChar(ch, isVariationSelector(nextCh) ? nextCh : 0, lang, variant);
256            if (utf16Pos == 0 || family != lastFamily) {
257                size_t start = utf16Pos;
258                // Workaround for Emoji keycap until we implement per-cluster font
259                // selection: if keycap is found in a different font that also
260                // supports previous char, attach previous char to the new run.
261                // Bug 7557244.
262                if (ch == KEYCAP && utf16Pos != 0 && family && family->getCoverage()->get(prevCh)) {
263                    const size_t prevChLength = U16_LENGTH(prevCh);
264                    run->end -= prevChLength;
265                    if (run->start == run->end) {
266                        result->pop_back();
267                    }
268                    start -= prevChLength;
269                }
270                Run dummy;
271                result->push_back(dummy);
272                run = &result->back();
273                if (family == NULL) {
274                    run->fakedFont.font = NULL;
275                } else {
276                    run->fakedFont = family->getClosestMatch(style);
277                }
278                lastFamily = family;
279                run->start = start;
280            }
281        }
282        prevCh = ch;
283        run->end = nextUtf16Pos;  // exclusive
284    } while (nextCh != kEndOfString);
285}
286
287MinikinFont* FontCollection::baseFont(FontStyle style) {
288    return baseFontFaked(style).font;
289}
290
291FakedFont FontCollection::baseFontFaked(FontStyle style) {
292    if (mFamilies.empty()) {
293        return FakedFont();
294    }
295    return mFamilies[0]->getClosestMatch(style);
296}
297
298uint32_t FontCollection::getId() const {
299    return mId;
300}
301
302void FontCollection::purgeFontFamilyHbFontCache() const {
303    assertMinikinLocked();
304    for (size_t i = 0; i < mFamilies.size(); ++i) {
305        mFamilies[i]->purgeHbFontCache();
306    }
307}
308
309}  // namespace android
310