FontCollection.cpp revision 7b221d97b7b64dc5ce457e19666d55d042e22e62
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.
117
118// Note that we may want to make the selection more dependent on
119// context, so for example a sequence of Devanagari, ZWJ, Devanagari
120// would get itemized as one run, even though by the rules the ZWJ
121// would go to the Latin font.
122const FontFamily* FontCollection::getFamilyForChar(uint32_t ch, FontLanguage lang,
123            int variant) const {
124    if (ch >= mMaxChar) {
125        return NULL;
126    }
127    const Range& range = mRanges[ch >> kLogCharsPerPage];
128#ifdef VERBOSE_DEBUG
129    ALOGD("querying range %d:%d\n", range.start, range.end);
130#endif
131    FontFamily* bestFamily = NULL;
132    int bestScore = -1;
133    for (size_t i = range.start; i < range.end; i++) {
134        const FontInstance* instance = mInstanceVec[i];
135        if (instance->mCoverage->get(ch)) {
136            FontFamily* family = instance->mFamily;
137            // First font family in collection always matches
138            if (mInstances[0].mFamily == family) {
139                return family;
140            }
141            int score = lang.match(family->lang()) * 2;
142            if (variant != 0 && variant == family->variant()) {
143                score++;
144            }
145            if (score > bestScore) {
146                bestScore = score;
147                bestFamily = family;
148            }
149        }
150    }
151    return bestFamily;
152}
153
154void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
155        vector<Run>* result) const {
156    FontLanguage lang = style.getLanguage();
157    int variant = style.getVariant();
158    const FontFamily* lastFamily = NULL;
159    Run* run = NULL;
160    int nShorts;
161    for (size_t i = 0; i < string_size; i += nShorts) {
162        nShorts = 1;
163        uint32_t ch = string[i];
164        // sigh, decode UTF-16 by hand here
165        if ((ch & 0xfc00) == 0xd800) {
166            if ((i + 1) < string_size) {
167                ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff);
168                nShorts = 2;
169            }
170        }
171        const FontFamily* family = getFamilyForChar(ch, lang, variant);
172        if (i == 0 || family != lastFamily) {
173            Run dummy;
174            result->push_back(dummy);
175            run = &result->back();
176            if (family == NULL) {
177                run->font = NULL;  // maybe we should do something different here
178            } else {
179                run->font = family->getClosestMatch(style);
180                // TODO: simplify refcounting (FontCollection lifetime dominates)
181                run->font->RefLocked();
182            }
183            lastFamily = family;
184            run->start = i;
185        }
186        run->end = i + nShorts;
187    }
188}
189
190uint32_t FontCollection::getId() const {
191    return mId;
192}
193
194}  // namespace android
195