FontCollection.cpp revision 156acb18f53b32655abb34166ea737e4320ca366
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            continue;
52        }
53        family->RefLocked();
54        FontInstance dummy;
55        mInstances.push_back(dummy);  // emplace_back would be better
56        FontInstance* instance = &mInstances.back();
57        instance->mFamily = family;
58        instance->mCoverage = new SparseBitSet;
59#ifdef VERBOSE_DEBUG
60        ALOGD("closest match = %p, family size = %d\n", typeface, family->getNumFonts());
61#endif
62        const uint32_t cmapTag = MinikinFont::MakeTag('c', 'm', 'a', 'p');
63        size_t cmapSize = 0;
64        bool ok = typeface->GetTable(cmapTag, NULL, &cmapSize);
65        UniquePtr<uint8_t[]> cmapData(new uint8_t[cmapSize]);
66        ok = typeface->GetTable(cmapTag, cmapData.get(), &cmapSize);
67        CmapCoverage::getCoverage(*instance->mCoverage, cmapData.get(), cmapSize);
68#ifdef VERBOSE_DEBUG
69        ALOGD("font coverage length=%d, first ch=%x\n", instance->mCoverage->length(),
70                instance->mCoverage->nextSetBit(0));
71#endif
72        mMaxChar = max(mMaxChar, instance->mCoverage->length());
73        lastChar.push_back(instance->mCoverage->nextSetBit(0));
74    }
75    nTypefaces = mInstances.size();
76    LOG_ALWAYS_FATAL_IF(nTypefaces == 0,
77        "Font collection must have at least one valid typeface");
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    if (bestInstance == NULL) {
147        bestInstance = &mInstances[0];
148    }
149    return bestInstance;
150}
151
152const uint32_t NBSP = 0xa0;
153const uint32_t ZWJ = 0x200c;
154const uint32_t ZWNJ = 0x200d;
155// Characters where we want to continue using existing font run instead of
156// recomputing the best match in the fallback list.
157static const uint32_t stickyWhitelist[] = { '!', ',', '.', ':', ';', '?', NBSP, ZWJ, ZWNJ };
158
159static bool isStickyWhitelisted(uint32_t c) {
160    for (size_t i = 0; i < sizeof(stickyWhitelist) / sizeof(stickyWhitelist[0]); i++) {
161        if (stickyWhitelist[i] == c) return true;
162    }
163    return false;
164}
165
166void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
167        vector<Run>* result) const {
168    FontLanguage lang = style.getLanguage();
169    int variant = style.getVariant();
170    const FontInstance* lastInstance = NULL;
171    Run* run = NULL;
172    int nShorts;
173    for (size_t i = 0; i < string_size; i += nShorts) {
174        nShorts = 1;
175        uint32_t ch = string[i];
176        // sigh, decode UTF-16 by hand here
177        if ((ch & 0xfc00) == 0xd800) {
178            if ((i + 1) < string_size) {
179                ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff);
180                nShorts = 2;
181            }
182        }
183        // Continue using existing font as long as it has coverage and is whitelisted
184        if (lastInstance == NULL
185                || !(isStickyWhitelisted(ch) && lastInstance->mCoverage->get(ch))) {
186            const FontInstance* instance = getInstanceForChar(ch, lang, variant);
187            if (i == 0 || instance != lastInstance) {
188                Run dummy;
189                result->push_back(dummy);
190                run = &result->back();
191                if (instance == NULL) {
192                    run->fakedFont.font = NULL;
193                } else {
194                    run->fakedFont = instance->mFamily->getClosestMatch(style);
195                }
196                lastInstance = instance;
197                run->start = i;
198            }
199        }
200        run->end = i + nShorts;
201    }
202}
203
204MinikinFont* FontCollection::baseFont(FontStyle style) {
205    return baseFontFaked(style).font;
206}
207
208FakedFont FontCollection::baseFontFaked(FontStyle style) {
209    if (mInstances.empty()) {
210        return FakedFont();
211    }
212    return mInstances[0].mFamily->getClosestMatch(style);
213}
214
215uint32_t FontCollection::getId() const {
216    return mId;
217}
218
219}  // namespace android
220