FontCollection.cpp 7.7 KB
Newer Older
R
Raph Levien 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17 18 19 20
// #define VERBOSE_DEBUG

#define LOG_TAG "Minikin"
#include <cutils/log.h>
R
Raph Levien 已提交
21

22 23 24
#include "unicode/unistr.h"
#include "unicode/unorm2.h"

25
#include "MinikinInternal.h"
R
Raph Levien 已提交
26 27 28 29 30 31 32 33 34 35 36
#include <minikin/FontCollection.h>

using std::vector;

namespace android {

template <typename T>
static inline T max(T a, T b) {
    return a>b ? a : b;
}

37 38
uint32_t FontCollection::sNextId = 0;

R
Raph Levien 已提交
39 40
FontCollection::FontCollection(const vector<FontFamily*>& typefaces) :
    mMaxChar(0) {
41
    AutoMutex _l(gMinikinLock);
42
    mId = sNextId++;
R
Raph Levien 已提交
43 44 45
    vector<uint32_t> lastChar;
    size_t nTypefaces = typefaces.size();
#ifdef VERBOSE_DEBUG
46
    ALOGD("nTypefaces = %d\n", nTypefaces);
R
Raph Levien 已提交
47 48 49 50
#endif
    const FontStyle defaultStyle;
    for (size_t i = 0; i < nTypefaces; i++) {
        FontFamily* family = typefaces[i];
R
Raph Levien 已提交
51
        MinikinFont* typeface = family->getClosestMatch(defaultStyle).font;
52 53 54
        if (typeface == NULL) {
            continue;
        }
55
        family->RefLocked();
56 57 58 59
        mFamilies.push_back(family);  // emplace_back would be better
        const SparseBitSet* coverage = family->getCoverage();
        mMaxChar = max(mMaxChar, coverage->length());
        lastChar.push_back(coverage->nextSetBit(0));
R
Raph Levien 已提交
60
    }
61
    nTypefaces = mFamilies.size();
62 63
    LOG_ALWAYS_FATAL_IF(nTypefaces == 0,
        "Font collection must have at least one valid typeface");
64
    size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage;
R
Raph Levien 已提交
65 66 67 68 69 70
    size_t offset = 0;
    for (size_t i = 0; i < nPages; i++) {
        Range dummy;
        mRanges.push_back(dummy);
        Range* range = &mRanges.back();
#ifdef VERBOSE_DEBUG
71
        ALOGD("i=%d: range start = %d\n", i, offset);
R
Raph Levien 已提交
72 73 74 75
#endif
        range->start = offset;
        for (size_t j = 0; j < nTypefaces; j++) {
            if (lastChar[j] < (i + 1) << kLogCharsPerPage) {
76 77
                FontFamily* family = mFamilies[j];
                mFamilyVec.push_back(family);
R
Raph Levien 已提交
78
                offset++;
79
                uint32_t nextChar = family->getCoverage()->nextSetBit((i + 1) << kLogCharsPerPage);
R
Raph Levien 已提交
80
#ifdef VERBOSE_DEBUG
81
                ALOGD("nextChar = %d (j = %d)\n", nextChar, j);
R
Raph Levien 已提交
82 83 84 85 86 87 88 89 90
#endif
                lastChar[j] = nextChar;
            }
        }
        range->end = offset;
    }
}

FontCollection::~FontCollection() {
91 92
    for (size_t i = 0; i < mFamilies.size(); i++) {
        mFamilies[i]->UnrefLocked();
R
Raph Levien 已提交
93 94 95
    }
}

R
Raph Levien 已提交
96 97 98 99 100 101
// Implement heuristic for choosing best-match font. Here are the rules:
// 1. If first font in the collection has the character, it wins.
// 2. If a font matches both language and script, it gets a score of 4.
// 3. If a font matches just language, it gets a score of 2.
// 4. Matching the "compact" or "elegant" variant adds one to the score.
// 5. Highest score wins, with ties resolved to the first font.
102
FontFamily* FontCollection::getFamilyForChar(uint32_t ch,
103
            FontLanguage lang, int variant) const {
R
Raph Levien 已提交
104 105 106 107 108
    if (ch >= mMaxChar) {
        return NULL;
    }
    const Range& range = mRanges[ch >> kLogCharsPerPage];
#ifdef VERBOSE_DEBUG
109
    ALOGD("querying range %d:%d\n", range.start, range.end);
R
Raph Levien 已提交
110
#endif
111
    FontFamily* bestFamily = NULL;
R
Raph Levien 已提交
112
    int bestScore = -1;
R
Raph Levien 已提交
113
    for (size_t i = range.start; i < range.end; i++) {
114 115
        FontFamily* family = mFamilyVec[i];
        if (family->getCoverage()->get(ch)) {
R
Raph Levien 已提交
116
            // First font family in collection always matches
117 118
            if (mFamilies[0] == family) {
                return family;
R
Raph Levien 已提交
119 120 121 122 123 124 125
            }
            int score = lang.match(family->lang()) * 2;
            if (variant != 0 && variant == family->variant()) {
                score++;
            }
            if (score > bestScore) {
                bestScore = score;
126
                bestFamily = family;
R
Raph Levien 已提交
127
            }
R
Raph Levien 已提交
128 129
        }
    }
130
    if (bestFamily == NULL && !mFamilyVec.empty()) {
131 132 133 134 135 136 137 138
        UErrorCode errorCode = U_ZERO_ERROR;
        const UNormalizer2* normalizer = unorm2_getNFDInstance(&errorCode);
        if (U_SUCCESS(errorCode)) {
            UChar decomposed[4];
            int len = unorm2_getRawDecomposition(normalizer, ch, decomposed, 4, &errorCode);
            if (U_SUCCESS(errorCode) && len > 0) {
                int off = 0;
                U16_NEXT_UNSAFE(decomposed, off, ch);
139
                return getFamilyForChar(ch, lang, variant);
140 141
            }
        }
142
        bestFamily = mFamilies[0];
143
    }
144
    return bestFamily;
R
Raph Levien 已提交
145 146
}

R
Raph Levien 已提交
147 148 149
const uint32_t NBSP = 0xa0;
const uint32_t ZWJ = 0x200c;
const uint32_t ZWNJ = 0x200d;
150 151
const uint32_t KEYCAP = 0x20e3;

R
Raph Levien 已提交
152 153
// Characters where we want to continue using existing font run instead of
// recomputing the best match in the fallback list.
154
static const uint32_t stickyWhitelist[] = { '!', ',', '.', ':', ';', '?', NBSP, ZWJ, ZWNJ, KEYCAP };
R
Raph Levien 已提交
155 156 157 158 159 160 161 162

static bool isStickyWhitelisted(uint32_t c) {
    for (size_t i = 0; i < sizeof(stickyWhitelist) / sizeof(stickyWhitelist[0]); i++) {
        if (stickyWhitelist[i] == c) return true;
    }
    return false;
}

R
Raph Levien 已提交
163 164
void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style,
        vector<Run>* result) const {
R
Raph Levien 已提交
165 166
    FontLanguage lang = style.getLanguage();
    int variant = style.getVariant();
167
    FontFamily* lastFamily = NULL;
R
Raph Levien 已提交
168 169 170 171 172 173 174 175 176 177 178 179
    Run* run = NULL;
    int nShorts;
    for (size_t i = 0; i < string_size; i += nShorts) {
        nShorts = 1;
        uint32_t ch = string[i];
        // sigh, decode UTF-16 by hand here
        if ((ch & 0xfc00) == 0xd800) {
            if ((i + 1) < string_size) {
                ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff);
                nShorts = 2;
            }
        }
R
Raph Levien 已提交
180
        // Continue using existing font as long as it has coverage and is whitelisted
181 182 183 184
        if (lastFamily == NULL
                || !(isStickyWhitelisted(ch) && lastFamily->getCoverage()->get(ch))) {
            FontFamily* family = getFamilyForChar(ch, lang, variant);
            if (i == 0 || family != lastFamily) {
185 186 187 188 189 190
                size_t start = i;
                // Workaround for Emoji keycap until we implement per-cluster font
                // selection: if keycap is found in a different font that also
                // supports previous char, attach previous char to the new run.
                // Only handles non-surrogate characters.
                // Bug 7557244.
191
                if (ch == KEYCAP && i && family && family->getCoverage()->get(string[i - 1])) {
192 193 194 195 196 197
                    run->end--;
                    if (run->start == run->end) {
                        result->pop_back();
                    }
                    start--;
                }
198 199 200
                Run dummy;
                result->push_back(dummy);
                run = &result->back();
201
                if (family == NULL) {
R
Raph Levien 已提交
202
                    run->fakedFont.font = NULL;
203
                } else {
204
                    run->fakedFont = family->getClosestMatch(style);
205
                }
206
                lastFamily = family;
207
                run->start = start;
R
Raph Levien 已提交
208 209 210 211 212 213
            }
        }
        run->end = i + nShorts;
    }
}

214
MinikinFont* FontCollection::baseFont(FontStyle style) {
R
Raph Levien 已提交
215 216 217 218
    return baseFontFaked(style).font;
}

FakedFont FontCollection::baseFontFaked(FontStyle style) {
219
    if (mFamilies.empty()) {
R
Raph Levien 已提交
220
        return FakedFont();
221
    }
222
    return mFamilies[0]->getClosestMatch(style);
223 224
}

225 226 227 228
uint32_t FontCollection::getId() const {
    return mId;
}

R
Raph Levien 已提交
229
}  // namespace android