Layout.cpp revision 6c4c098cbd37eccef483ab1986127250b4d2ddf2
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 LOG_TAG "Minikin"
18#include <cutils/log.h>
19
20#include <math.h>
21
22#include <algorithm>
23#include <fstream>
24#include <iostream>  // for debugging
25#include <string>
26#include <vector>
27
28#include <utils/JenkinsHash.h>
29#include <utils/LruCache.h>
30#include <utils/Singleton.h>
31#include <utils/String16.h>
32
33#include <unicode/ubidi.h>
34#include <hb-icu.h>
35#include <hb-ot.h>
36
37#include "FontLanguageListCache.h"
38#include "LayoutUtils.h"
39#include "HbFaceCache.h"
40#include "MinikinInternal.h"
41#include <minikin/MinikinFontFreeType.h>
42#include <minikin/Layout.h>
43
44using std::string;
45using std::vector;
46
47namespace minikin {
48
49Bitmap::Bitmap(int width, int height) : width(width), height(height) {
50    buf = new uint8_t[width * height]();
51}
52
53Bitmap::~Bitmap() {
54    delete[] buf;
55}
56
57void Bitmap::writePnm(std::ofstream &o) const {
58    o << "P5" << std::endl;
59    o << width << " " << height << std::endl;
60    o << "255" << std::endl;
61    o.write((const char *)buf, width * height);
62    o.close();
63}
64
65void Bitmap::drawGlyph(const android::GlyphBitmap& bitmap, int x, int y) {
66    int bmw = bitmap.width;
67    int bmh = bitmap.height;
68    x += bitmap.left;
69    y -= bitmap.top;
70    int x0 = std::max(0, x);
71    int x1 = std::min(width, x + bmw);
72    int y0 = std::max(0, y);
73    int y1 = std::min(height, y + bmh);
74    const unsigned char* src = bitmap.buffer + (y0 - y) * bmw + (x0 - x);
75    uint8_t* dst = buf + y0 * width;
76    for (int yy = y0; yy < y1; yy++) {
77        for (int xx = x0; xx < x1; xx++) {
78            int pixel = (int)dst[xx] + (int)src[xx - x];
79            pixel = pixel > 0xff ? 0xff : pixel;
80            dst[xx] = pixel;
81        }
82        src += bmw;
83        dst += width;
84    }
85}
86
87} // namespace minikin
88
89namespace android {
90
91const int kDirection_Mask = 0x1;
92
93struct LayoutContext {
94    MinikinPaint paint;
95    FontStyle style;
96    std::vector<hb_font_t*> hbFonts;  // parallel to mFaces
97
98    void clearHbFonts() {
99        for (size_t i = 0; i < hbFonts.size(); i++) {
100            hb_font_destroy(hbFonts[i]);
101        }
102        hbFonts.clear();
103    }
104};
105
106// Layout cache datatypes
107
108class LayoutCacheKey {
109public:
110    LayoutCacheKey(const FontCollection* collection, const MinikinPaint& paint, FontStyle style,
111            const uint16_t* chars, size_t start, size_t count, size_t nchars, bool dir)
112            : mChars(chars), mNchars(nchars),
113            mStart(start), mCount(count), mId(collection->getId()), mStyle(style),
114            mSize(paint.size), mScaleX(paint.scaleX), mSkewX(paint.skewX),
115            mLetterSpacing(paint.letterSpacing),
116            mPaintFlags(paint.paintFlags), mHyphenEdit(paint.hyphenEdit), mIsRtl(dir) {
117    }
118    bool operator==(const LayoutCacheKey &other) const;
119    hash_t hash() const;
120
121    void copyText() {
122        uint16_t* charsCopy = new uint16_t[mNchars];
123        memcpy(charsCopy, mChars, mNchars * sizeof(uint16_t));
124        mChars = charsCopy;
125    }
126    void freeText() {
127        delete[] mChars;
128        mChars = NULL;
129    }
130
131    void doLayout(Layout* layout, LayoutContext* ctx, const FontCollection* collection) const {
132        layout->setFontCollection(collection);
133        layout->mAdvances.resize(mCount, 0);
134        ctx->clearHbFonts();
135        collection->purgeFontFamilyHbFontCache();
136        layout->doLayoutRun(mChars, mStart, mCount, mNchars, mIsRtl, ctx);
137    }
138
139private:
140    const uint16_t* mChars;
141    size_t mNchars;
142    size_t mStart;
143    size_t mCount;
144    uint32_t mId;  // for the font collection
145    FontStyle mStyle;
146    float mSize;
147    float mScaleX;
148    float mSkewX;
149    float mLetterSpacing;
150    int32_t mPaintFlags;
151    HyphenEdit mHyphenEdit;
152    bool mIsRtl;
153    // Note: any fields added to MinikinPaint must also be reflected here.
154    // TODO: language matching (possibly integrate into style)
155};
156
157class LayoutCache : private OnEntryRemoved<LayoutCacheKey, Layout*> {
158public:
159    LayoutCache() : mCache(kMaxEntries) {
160        mCache.setOnEntryRemovedListener(this);
161    }
162
163    void clear() {
164        mCache.clear();
165    }
166
167    Layout* get(LayoutCacheKey& key, LayoutContext* ctx, const FontCollection* collection) {
168        Layout* layout = mCache.get(key);
169        if (layout == NULL) {
170            key.copyText();
171            layout = new Layout();
172            key.doLayout(layout, ctx, collection);
173            mCache.put(key, layout);
174        }
175        return layout;
176    }
177
178private:
179    // callback for OnEntryRemoved
180    void operator()(LayoutCacheKey& key, Layout*& value) {
181        key.freeText();
182        delete value;
183    }
184
185    LruCache<LayoutCacheKey, Layout*> mCache;
186
187    //static const size_t kMaxEntries = LruCache<LayoutCacheKey, Layout*>::kUnlimitedCapacity;
188
189    // TODO: eviction based on memory footprint; for now, we just use a constant
190    // number of strings
191    static const size_t kMaxEntries = 5000;
192};
193
194static unsigned int disabledDecomposeCompatibility(hb_unicode_funcs_t*, hb_codepoint_t,
195                                                   hb_codepoint_t*, void*) {
196    return 0;
197}
198
199class LayoutEngine : public Singleton<LayoutEngine> {
200public:
201    LayoutEngine() {
202        unicodeFunctions = hb_unicode_funcs_create(hb_icu_get_unicode_funcs());
203        /* Disable the function used for compatibility decomposition */
204        hb_unicode_funcs_set_decompose_compatibility_func(
205                unicodeFunctions, disabledDecomposeCompatibility, NULL, NULL);
206        hbBuffer = hb_buffer_create();
207        hb_buffer_set_unicode_funcs(hbBuffer, unicodeFunctions);
208    }
209
210    hb_buffer_t* hbBuffer;
211    hb_unicode_funcs_t* unicodeFunctions;
212    LayoutCache layoutCache;
213};
214
215ANDROID_SINGLETON_STATIC_INSTANCE(LayoutEngine);
216
217bool LayoutCacheKey::operator==(const LayoutCacheKey& other) const {
218    return mId == other.mId
219            && mStart == other.mStart
220            && mCount == other.mCount
221            && mStyle == other.mStyle
222            && mSize == other.mSize
223            && mScaleX == other.mScaleX
224            && mSkewX == other.mSkewX
225            && mLetterSpacing == other.mLetterSpacing
226            && mPaintFlags == other.mPaintFlags
227            && mHyphenEdit == other.mHyphenEdit
228            && mIsRtl == other.mIsRtl
229            && mNchars == other.mNchars
230            && !memcmp(mChars, other.mChars, mNchars * sizeof(uint16_t));
231}
232
233hash_t LayoutCacheKey::hash() const {
234    uint32_t hash = JenkinsHashMix(0, mId);
235    hash = JenkinsHashMix(hash, mStart);
236    hash = JenkinsHashMix(hash, mCount);
237    hash = JenkinsHashMix(hash, hash_type(mStyle));
238    hash = JenkinsHashMix(hash, hash_type(mSize));
239    hash = JenkinsHashMix(hash, hash_type(mScaleX));
240    hash = JenkinsHashMix(hash, hash_type(mSkewX));
241    hash = JenkinsHashMix(hash, hash_type(mLetterSpacing));
242    hash = JenkinsHashMix(hash, hash_type(mPaintFlags));
243    hash = JenkinsHashMix(hash, hash_type(mHyphenEdit.hasHyphen()));
244    hash = JenkinsHashMix(hash, hash_type(mIsRtl));
245    hash = JenkinsHashMixShorts(hash, mChars, mNchars);
246    return JenkinsHashWhiten(hash);
247}
248
249hash_t hash_type(const LayoutCacheKey& key) {
250    return key.hash();
251}
252
253void MinikinRect::join(const MinikinRect& r) {
254    if (isEmpty()) {
255        set(r);
256    } else if (!r.isEmpty()) {
257        mLeft = std::min(mLeft, r.mLeft);
258        mTop = std::min(mTop, r.mTop);
259        mRight = std::max(mRight, r.mRight);
260        mBottom = std::max(mBottom, r.mBottom);
261    }
262}
263
264// Deprecated. Remove when callers are removed.
265void Layout::init() {
266}
267
268void Layout::reset() {
269    mGlyphs.clear();
270    mFaces.clear();
271    mBounds.setEmpty();
272    mAdvances.clear();
273    mAdvance = 0;
274}
275
276void Layout::setFontCollection(const FontCollection* collection) {
277    mCollection = collection;
278}
279
280static hb_position_t harfbuzzGetGlyphHorizontalAdvance(hb_font_t* /* hbFont */, void* fontData,
281        hb_codepoint_t glyph, void* /* userData */) {
282    MinikinPaint* paint = reinterpret_cast<MinikinPaint*>(fontData);
283    MinikinFont* font = paint->font;
284    float advance = font->GetHorizontalAdvance(glyph, *paint);
285    return 256 * advance + 0.5;
286}
287
288static hb_bool_t harfbuzzGetGlyphHorizontalOrigin(hb_font_t* /* hbFont */, void* /* fontData */,
289        hb_codepoint_t /* glyph */, hb_position_t* /* x */, hb_position_t* /* y */,
290        void* /* userData */) {
291    // Just return true, following the way that Harfbuzz-FreeType
292    // implementation does.
293    return true;
294}
295
296hb_font_funcs_t* getHbFontFuncs() {
297    static hb_font_funcs_t* hbFontFuncs = 0;
298
299    if (hbFontFuncs == 0) {
300        hbFontFuncs = hb_font_funcs_create();
301        hb_font_funcs_set_glyph_h_advance_func(hbFontFuncs, harfbuzzGetGlyphHorizontalAdvance, 0, 0);
302        hb_font_funcs_set_glyph_h_origin_func(hbFontFuncs, harfbuzzGetGlyphHorizontalOrigin, 0, 0);
303        hb_font_funcs_make_immutable(hbFontFuncs);
304    }
305    return hbFontFuncs;
306}
307
308static hb_font_t* create_hb_font(MinikinFont* minikinFont, MinikinPaint* minikinPaint) {
309    hb_face_t* face = getHbFaceLocked(minikinFont);
310    hb_font_t* parent_font = hb_font_create(face);
311    hb_ot_font_set_funcs(parent_font);
312
313    unsigned int upem = hb_face_get_upem(face);
314    hb_font_set_scale(parent_font, upem, upem);
315
316    hb_font_t* font = hb_font_create_sub_font(parent_font);
317    hb_font_destroy(parent_font);
318
319    hb_font_set_funcs(font, getHbFontFuncs(), minikinPaint, 0);
320    return font;
321}
322
323static float HBFixedToFloat(hb_position_t v)
324{
325    return scalbnf (v, -8);
326}
327
328static hb_position_t HBFloatToFixed(float v)
329{
330    return scalbnf (v, +8);
331}
332
333void Layout::dump() const {
334    for (size_t i = 0; i < mGlyphs.size(); i++) {
335        const LayoutGlyph& glyph = mGlyphs[i];
336        std::cout << glyph.glyph_id << ": " << glyph.x << ", " << glyph.y << std::endl;
337    }
338}
339
340int Layout::findFace(FakedFont face, LayoutContext* ctx) {
341    unsigned int ix;
342    for (ix = 0; ix < mFaces.size(); ix++) {
343        if (mFaces[ix].font == face.font) {
344            return ix;
345        }
346    }
347    mFaces.push_back(face);
348    // Note: ctx == NULL means we're copying from the cache, no need to create
349    // corresponding hb_font object.
350    if (ctx != NULL) {
351        hb_font_t* font = create_hb_font(face.font, &ctx->paint);
352        ctx->hbFonts.push_back(font);
353    }
354    return ix;
355}
356
357static hb_script_t codePointToScript(hb_codepoint_t codepoint) {
358    static hb_unicode_funcs_t* u = 0;
359    if (!u) {
360        u = LayoutEngine::getInstance().unicodeFunctions;
361    }
362    return hb_unicode_script(u, codepoint);
363}
364
365static hb_codepoint_t decodeUtf16(const uint16_t* chars, size_t len, ssize_t* iter) {
366    const uint16_t v = chars[(*iter)++];
367    // test whether v in (0xd800..0xdfff), lead or trail surrogate
368    if ((v & 0xf800) == 0xd800) {
369        // test whether v in (0xd800..0xdbff), lead surrogate
370        if (size_t(*iter) < len && (v & 0xfc00) == 0xd800) {
371            const uint16_t v2 = chars[(*iter)++];
372            // test whether v2 in (0xdc00..0xdfff), trail surrogate
373            if ((v2 & 0xfc00) == 0xdc00) {
374                // (0xd800 0xdc00) in utf-16 maps to 0x10000 in ucs-32
375                const hb_codepoint_t delta = (0xd800 << 10) + 0xdc00 - 0x10000;
376                return (((hb_codepoint_t)v) << 10) + v2 - delta;
377            }
378            (*iter) -= 1;
379            return 0xFFFDu;
380        } else {
381            return 0xFFFDu;
382        }
383    } else {
384        return v;
385    }
386}
387
388static hb_script_t getScriptRun(const uint16_t* chars, size_t len, ssize_t* iter) {
389    if (size_t(*iter) == len) {
390        return HB_SCRIPT_UNKNOWN;
391    }
392    uint32_t cp = decodeUtf16(chars, len, iter);
393    hb_script_t current_script = codePointToScript(cp);
394    for (;;) {
395        if (size_t(*iter) == len)
396            break;
397        const ssize_t prev_iter = *iter;
398        cp = decodeUtf16(chars, len, iter);
399        const hb_script_t script = codePointToScript(cp);
400        if (script != current_script) {
401            if (current_script == HB_SCRIPT_INHERITED ||
402                current_script == HB_SCRIPT_COMMON) {
403                current_script = script;
404            } else if (script == HB_SCRIPT_INHERITED ||
405                script == HB_SCRIPT_COMMON) {
406                continue;
407            } else {
408                *iter = prev_iter;
409                break;
410            }
411        }
412    }
413    if (current_script == HB_SCRIPT_INHERITED) {
414        current_script = HB_SCRIPT_COMMON;
415    }
416
417    return current_script;
418}
419
420/**
421 * Disable certain scripts (mostly those with cursive connection) from having letterspacing
422 * applied. See https://github.com/behdad/harfbuzz/issues/64 for more details.
423 */
424static bool isScriptOkForLetterspacing(hb_script_t script) {
425    return !(
426            script == HB_SCRIPT_ARABIC ||
427            script == HB_SCRIPT_NKO ||
428            script == HB_SCRIPT_PSALTER_PAHLAVI ||
429            script == HB_SCRIPT_MANDAIC ||
430            script == HB_SCRIPT_MONGOLIAN ||
431            script == HB_SCRIPT_PHAGS_PA ||
432            script == HB_SCRIPT_DEVANAGARI ||
433            script == HB_SCRIPT_BENGALI ||
434            script == HB_SCRIPT_GURMUKHI ||
435            script == HB_SCRIPT_MODI ||
436            script == HB_SCRIPT_SHARADA ||
437            script == HB_SCRIPT_SYLOTI_NAGRI ||
438            script == HB_SCRIPT_TIRHUTA ||
439            script == HB_SCRIPT_OGHAM
440            );
441}
442
443class BidiText {
444public:
445    class Iter {
446    public:
447        struct RunInfo {
448            int32_t mRunStart;
449            int32_t mRunLength;
450            bool mIsRtl;
451        };
452
453        Iter(UBiDi* bidi, size_t start, size_t end, size_t runIndex, size_t runCount, bool isRtl);
454
455        bool operator!= (const Iter& other) const {
456            return mIsEnd != other.mIsEnd || mNextRunIndex != other.mNextRunIndex
457                    || mBidi != other.mBidi;
458        }
459
460        const RunInfo& operator* () const {
461            return mRunInfo;
462        }
463
464        const Iter& operator++ () {
465            updateRunInfo();
466            return *this;
467        }
468
469    private:
470        UBiDi* const mBidi;
471        bool mIsEnd;
472        size_t mNextRunIndex;
473        const size_t mRunCount;
474        const int32_t mStart;
475        const int32_t mEnd;
476        RunInfo mRunInfo;
477
478        void updateRunInfo();
479    };
480
481    BidiText(const uint16_t* buf, size_t start, size_t count, size_t bufSize, int bidiFlags);
482
483    ~BidiText() {
484        if (mBidi) {
485            ubidi_close(mBidi);
486        }
487    }
488
489    Iter begin () const {
490        return Iter(mBidi, mStart, mEnd, 0, mRunCount, mIsRtl);
491    }
492
493    Iter end() const {
494        return Iter(mBidi, mStart, mEnd, mRunCount, mRunCount, mIsRtl);
495    }
496
497private:
498    const size_t mStart;
499    const size_t mEnd;
500    const size_t mBufSize;
501    UBiDi* mBidi;
502    size_t mRunCount;
503    bool mIsRtl;
504
505    DISALLOW_COPY_AND_ASSIGN(BidiText);
506};
507
508BidiText::Iter::Iter(UBiDi* bidi, size_t start, size_t end, size_t runIndex, size_t runCount,
509        bool isRtl)
510    : mBidi(bidi), mIsEnd(runIndex == runCount), mNextRunIndex(runIndex), mRunCount(runCount),
511      mStart(start), mEnd(end), mRunInfo() {
512    if (mRunCount == 1) {
513        mRunInfo.mRunStart = start;
514        mRunInfo.mRunLength = end - start;
515        mRunInfo.mIsRtl = isRtl;
516        mNextRunIndex = mRunCount;
517        return;
518    }
519    updateRunInfo();
520}
521
522void BidiText::Iter::updateRunInfo() {
523    if (mNextRunIndex == mRunCount) {
524        // All runs have been iterated.
525        mIsEnd = true;
526        return;
527    }
528    int32_t startRun = -1;
529    int32_t lengthRun = -1;
530    const UBiDiDirection runDir = ubidi_getVisualRun(mBidi, mNextRunIndex, &startRun, &lengthRun);
531    mNextRunIndex++;
532    if (startRun == -1 || lengthRun == -1) {
533        ALOGE("invalid visual run");
534        // skip the invalid run.
535        updateRunInfo();
536        return;
537    }
538    const int32_t runEnd = std::min(startRun + lengthRun, mEnd);
539    mRunInfo.mRunStart = std::max(startRun, mStart);
540    mRunInfo.mRunLength = runEnd - mRunInfo.mRunStart;
541    if (mRunInfo.mRunLength <= 0) {
542        // skip the empty run.
543        updateRunInfo();
544        return;
545    }
546    mRunInfo.mIsRtl = (runDir == UBIDI_RTL);
547}
548
549BidiText::BidiText(const uint16_t* buf, size_t start, size_t count, size_t bufSize, int bidiFlags)
550    : mStart(start), mEnd(start + count), mBufSize(bufSize), mBidi(NULL), mRunCount(1),
551      mIsRtl((bidiFlags & kDirection_Mask) != 0) {
552    if (bidiFlags == kBidi_Force_LTR || bidiFlags == kBidi_Force_RTL) {
553        // force single run.
554        return;
555    }
556    mBidi = ubidi_open();
557    if (!mBidi) {
558        ALOGE("error creating bidi object");
559        return;
560    }
561    UErrorCode status = U_ZERO_ERROR;
562    UBiDiLevel bidiReq = bidiFlags;
563    if (bidiFlags == kBidi_Default_LTR) {
564        bidiReq = UBIDI_DEFAULT_LTR;
565    } else if (bidiFlags == kBidi_Default_RTL) {
566        bidiReq = UBIDI_DEFAULT_RTL;
567    }
568    ubidi_setPara(mBidi, buf, mBufSize, bidiReq, NULL, &status);
569    if (!U_SUCCESS(status)) {
570        ALOGE("error calling ubidi_setPara, status = %d", status);
571        return;
572    }
573    const int paraDir = ubidi_getParaLevel(mBidi) & kDirection_Mask;
574    const ssize_t rc = ubidi_countRuns(mBidi, &status);
575    if (!U_SUCCESS(status) || rc < 0) {
576        ALOGW("error counting bidi runs, status = %d", status);
577    }
578    if (!U_SUCCESS(status) || rc <= 1) {
579        mIsRtl = (paraDir == kBidi_RTL);
580        return;
581    }
582    mRunCount = rc;
583}
584
585void Layout::doLayout(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
586        int bidiFlags, const FontStyle &style, const MinikinPaint &paint) {
587    AutoMutex _l(gMinikinLock);
588
589    LayoutContext ctx;
590    ctx.style = style;
591    ctx.paint = paint;
592
593    reset();
594    mAdvances.resize(count, 0);
595
596    for (const BidiText::Iter::RunInfo& runInfo : BidiText(buf, start, count, bufSize, bidiFlags)) {
597        doLayoutRunCached(buf, runInfo.mRunStart, runInfo.mRunLength, bufSize, runInfo.mIsRtl, &ctx,
598                start);
599    }
600    ctx.clearHbFonts();
601    mCollection->purgeFontFamilyHbFontCache();
602}
603
604void Layout::doLayoutRunCached(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
605        bool isRtl, LayoutContext* ctx, size_t dstStart) {
606    HyphenEdit hyphen = ctx->paint.hyphenEdit;
607    if (!isRtl) {
608        // left to right
609        size_t wordstart =
610                start == bufSize ? start : getPrevWordBreakForCache(buf, start + 1, bufSize);
611        size_t wordend;
612        for (size_t iter = start; iter < start + count; iter = wordend) {
613            wordend = getNextWordBreakForCache(buf, iter, bufSize);
614            // Only apply hyphen to the last word in the string.
615            ctx->paint.hyphenEdit = wordend >= start + count ? hyphen : HyphenEdit();
616            size_t wordcount = std::min(start + count, wordend) - iter;
617            doLayoutWord(buf + wordstart, iter - wordstart, wordcount, wordend - wordstart,
618                    isRtl, ctx, iter - dstStart);
619            wordstart = wordend;
620        }
621    } else {
622        // right to left
623        size_t wordstart;
624        size_t end = start + count;
625        size_t wordend = end == 0 ? 0 : getNextWordBreakForCache(buf, end - 1, bufSize);
626        for (size_t iter = end; iter > start; iter = wordstart) {
627            wordstart = getPrevWordBreakForCache(buf, iter, bufSize);
628            // Only apply hyphen to the last (leftmost) word in the string.
629            ctx->paint.hyphenEdit = iter == end ? hyphen : HyphenEdit();
630            size_t bufStart = std::max(start, wordstart);
631            doLayoutWord(buf + wordstart, bufStart - wordstart, iter - bufStart,
632                    wordend - wordstart, isRtl, ctx, bufStart - dstStart);
633            wordend = wordstart;
634        }
635    }
636}
637
638void Layout::doLayoutWord(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
639        bool isRtl, LayoutContext* ctx, size_t bufStart) {
640    LayoutCache& cache = LayoutEngine::getInstance().layoutCache;
641    LayoutCacheKey key(mCollection, ctx->paint, ctx->style, buf, start, count, bufSize, isRtl);
642    bool skipCache = ctx->paint.skipCache();
643    if (skipCache) {
644        Layout layout;
645        key.doLayout(&layout, ctx, mCollection);
646        appendLayout(&layout, bufStart);
647    } else {
648        Layout* layout = cache.get(key, ctx, mCollection);
649        appendLayout(layout, bufStart);
650    }
651}
652
653static void addFeatures(const string &str, vector<hb_feature_t>* features) {
654    if (!str.size())
655        return;
656
657    const char* start = str.c_str();
658    const char* end = start + str.size();
659
660    while (start < end) {
661        static hb_feature_t feature;
662        const char* p = strchr(start, ',');
663        if (!p)
664            p = end;
665        /* We do not allow setting features on ranges.  As such, reject any
666         * setting that has non-universal range. */
667        if (hb_feature_from_string (start, p - start, &feature)
668                && feature.start == 0 && feature.end == (unsigned int) -1)
669            features->push_back(feature);
670        start = p + 1;
671    }
672}
673
674void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
675        bool isRtl, LayoutContext* ctx) {
676    hb_buffer_t* buffer = LayoutEngine::getInstance().hbBuffer;
677    vector<FontCollection::Run> items;
678    mCollection->itemize(buf + start, count, ctx->style, &items);
679    if (isRtl) {
680        std::reverse(items.begin(), items.end());
681    }
682
683    vector<hb_feature_t> features;
684    // Disable default-on non-required ligature features if letter-spacing
685    // See http://dev.w3.org/csswg/css-text-3/#letter-spacing-property
686    // "When the effective spacing between two characters is not zero (due to
687    // either justification or a non-zero value of letter-spacing), user agents
688    // should not apply optional ligatures."
689    if (fabs(ctx->paint.letterSpacing) > 0.03)
690    {
691        static const hb_feature_t no_liga = { HB_TAG('l', 'i', 'g', 'a'), 0, 0, ~0u };
692        static const hb_feature_t no_clig = { HB_TAG('c', 'l', 'i', 'g'), 0, 0, ~0u };
693        features.push_back(no_liga);
694        features.push_back(no_clig);
695    }
696    addFeatures(ctx->paint.fontFeatureSettings, &features);
697
698    double size = ctx->paint.size;
699    double scaleX = ctx->paint.scaleX;
700
701    float x = mAdvance;
702    float y = 0;
703    for (size_t run_ix = 0; run_ix < items.size(); run_ix++) {
704        FontCollection::Run &run = items[run_ix];
705        if (run.fakedFont.font == NULL) {
706            ALOGE("no font for run starting u+%04x length %d", buf[run.start], run.end - run.start);
707            continue;
708        }
709        int font_ix = findFace(run.fakedFont, ctx);
710        ctx->paint.font = mFaces[font_ix].font;
711        ctx->paint.fakery = mFaces[font_ix].fakery;
712        hb_font_t* hbFont = ctx->hbFonts[font_ix];
713#ifdef VERBOSE_DEBUG
714        ALOGD("Run %zu, font %d [%d:%d]", run_ix, font_ix, run.start, run.end);
715#endif
716
717        hb_font_set_ppem(hbFont, size * scaleX, size);
718        hb_font_set_scale(hbFont, HBFloatToFixed(size * scaleX), HBFloatToFixed(size));
719
720        // TODO: if there are multiple scripts within a font in an RTL run,
721        // we need to reorder those runs. This is unlikely with our current
722        // font stack, but should be done for correctness.
723        ssize_t srunend;
724        for (ssize_t srunstart = run.start; srunstart < run.end; srunstart = srunend) {
725            srunend = srunstart;
726            hb_script_t script = getScriptRun(buf + start, run.end, &srunend);
727
728            double letterSpace = 0.0;
729            double letterSpaceHalfLeft = 0.0;
730            double letterSpaceHalfRight = 0.0;
731
732            if (ctx->paint.letterSpacing != 0.0 && isScriptOkForLetterspacing(script)) {
733                letterSpace = ctx->paint.letterSpacing * size * scaleX;
734                if ((ctx->paint.paintFlags & LinearTextFlag) == 0) {
735                    letterSpace = round(letterSpace);
736                    letterSpaceHalfLeft = floor(letterSpace * 0.5);
737                } else {
738                    letterSpaceHalfLeft = letterSpace * 0.5;
739                }
740                letterSpaceHalfRight = letterSpace - letterSpaceHalfLeft;
741            }
742
743            hb_buffer_clear_contents(buffer);
744            hb_buffer_set_script(buffer, script);
745            hb_buffer_set_direction(buffer, isRtl? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
746            const FontLanguages& langList =
747                    FontLanguageListCache::getById(ctx->style.getLanguageListId());
748            if (langList.size() != 0) {
749                // TODO: use all languages in langList.
750                string lang = langList[0].getString();
751                hb_buffer_set_language(buffer, hb_language_from_string(lang.c_str(), -1));
752            }
753            hb_buffer_add_utf16(buffer, buf, bufSize, srunstart + start, srunend - srunstart);
754            if (ctx->paint.hyphenEdit.hasHyphen() && srunend > srunstart) {
755                // TODO: check whether this is really the desired semantics. It could have the
756                // effect of assigning the hyphen width to a nonspacing mark
757                unsigned int lastCluster = start + srunend - 1;
758
759                hb_codepoint_t hyphenChar = 0x2010; // HYPHEN
760                hb_codepoint_t glyph;
761                // Fallback to ASCII HYPHEN-MINUS if the font didn't have a glyph for HYPHEN. Note
762                // that we intentionally don't do anything special if the font doesn't have a
763                // HYPHEN-MINUS either, so a tofu could be shown, hinting towards something
764                // missing.
765                if (!hb_font_get_glyph(hbFont, hyphenChar, 0, &glyph)) {
766                    hyphenChar = 0x002D; // HYPHEN-MINUS
767                }
768                hb_buffer_add(buffer, hyphenChar, lastCluster);
769            }
770            hb_shape(hbFont, buffer, features.empty() ? NULL : &features[0], features.size());
771            unsigned int numGlyphs;
772            hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, &numGlyphs);
773            hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buffer, NULL);
774            if (numGlyphs)
775            {
776                mAdvances[info[0].cluster - start] += letterSpaceHalfLeft;
777                x += letterSpaceHalfLeft;
778            }
779            for (unsigned int i = 0; i < numGlyphs; i++) {
780#ifdef VERBOSE_DEBUG
781                ALOGD("%d %d %d %d",
782                        positions[i].x_advance, positions[i].y_advance,
783                        positions[i].x_offset, positions[i].y_offset);
784                ALOGD("DoLayout %u: %f; %d, %d",
785                        info[i].codepoint, HBFixedToFloat(positions[i].x_advance),
786                        positions[i].x_offset, positions[i].y_offset);
787#endif
788                if (i > 0 && info[i - 1].cluster != info[i].cluster) {
789                    mAdvances[info[i - 1].cluster - start] += letterSpaceHalfRight;
790                    mAdvances[info[i].cluster - start] += letterSpaceHalfLeft;
791                    x += letterSpace;
792                }
793
794                hb_codepoint_t glyph_ix = info[i].codepoint;
795                float xoff = HBFixedToFloat(positions[i].x_offset);
796                float yoff = -HBFixedToFloat(positions[i].y_offset);
797                xoff += yoff * ctx->paint.skewX;
798                LayoutGlyph glyph = {font_ix, glyph_ix, x + xoff, y + yoff};
799                mGlyphs.push_back(glyph);
800                float xAdvance = HBFixedToFloat(positions[i].x_advance);
801                if ((ctx->paint.paintFlags & LinearTextFlag) == 0) {
802                    xAdvance = roundf(xAdvance);
803                }
804                MinikinRect glyphBounds;
805                ctx->paint.font->GetBounds(&glyphBounds, glyph_ix, ctx->paint);
806                glyphBounds.offset(x + xoff, y + yoff);
807                mBounds.join(glyphBounds);
808                if (info[i].cluster - start < count) {
809                    mAdvances[info[i].cluster - start] += xAdvance;
810                } else {
811                    ALOGE("cluster %zu (start %zu) out of bounds of count %zu",
812                        info[i].cluster - start, start, count);
813                }
814                x += xAdvance;
815            }
816            if (numGlyphs)
817            {
818                mAdvances[info[numGlyphs - 1].cluster - start] += letterSpaceHalfRight;
819                x += letterSpaceHalfRight;
820            }
821        }
822    }
823    mAdvance = x;
824}
825
826void Layout::appendLayout(Layout* src, size_t start) {
827    int fontMapStack[16];
828    int* fontMap;
829    if (src->mFaces.size() < sizeof(fontMapStack) / sizeof(fontMapStack[0])) {
830        fontMap = fontMapStack;
831    } else {
832        fontMap = new int[src->mFaces.size()];
833    }
834    for (size_t i = 0; i < src->mFaces.size(); i++) {
835        int font_ix = findFace(src->mFaces[i], NULL);
836        fontMap[i] = font_ix;
837    }
838    int x0 = mAdvance;
839    for (size_t i = 0; i < src->mGlyphs.size(); i++) {
840        LayoutGlyph& srcGlyph = src->mGlyphs[i];
841        int font_ix = fontMap[srcGlyph.font_ix];
842        unsigned int glyph_id = srcGlyph.glyph_id;
843        float x = x0 + srcGlyph.x;
844        float y = srcGlyph.y;
845        LayoutGlyph glyph = {font_ix, glyph_id, x, y};
846        mGlyphs.push_back(glyph);
847    }
848    for (size_t i = 0; i < src->mAdvances.size(); i++) {
849        mAdvances[i + start] = src->mAdvances[i];
850    }
851    MinikinRect srcBounds(src->mBounds);
852    srcBounds.offset(x0, 0);
853    mBounds.join(srcBounds);
854    mAdvance += src->mAdvance;
855
856    if (fontMap != fontMapStack) {
857        delete[] fontMap;
858    }
859}
860
861void Layout::draw(minikin::Bitmap* surface, int x0, int y0, float size) const {
862    /*
863    TODO: redo as MinikinPaint settings
864    if (mProps.hasTag(minikinHinting)) {
865        int hintflags = mProps.value(minikinHinting).getIntValue();
866        if (hintflags & 1) load_flags |= FT_LOAD_NO_HINTING;
867        if (hintflags & 2) load_flags |= FT_LOAD_NO_AUTOHINT;
868    }
869    */
870    for (size_t i = 0; i < mGlyphs.size(); i++) {
871        const LayoutGlyph& glyph = mGlyphs[i];
872        MinikinFont* mf = mFaces[glyph.font_ix].font;
873        MinikinFontFreeType* face = static_cast<MinikinFontFreeType*>(mf);
874        GlyphBitmap glyphBitmap;
875        MinikinPaint paint;
876        paint.size = size;
877        bool ok = face->Render(glyph.glyph_id, paint, &glyphBitmap);
878#ifdef VERBOSE_DEBUG
879        ALOGD("glyphBitmap.width=%d, glyphBitmap.height=%d (%d, %d) x=%f, y=%f, ok=%d",
880            glyphBitmap.width, glyphBitmap.height, glyphBitmap.left, glyphBitmap.top, glyph.x, glyph.y, ok);
881#endif
882        if (ok) {
883            surface->drawGlyph(glyphBitmap,
884                x0 + int(floor(glyph.x + 0.5)), y0 + int(floor(glyph.y + 0.5)));
885        }
886    }
887}
888
889size_t Layout::nGlyphs() const {
890    return mGlyphs.size();
891}
892
893MinikinFont* Layout::getFont(int i) const {
894    const LayoutGlyph& glyph = mGlyphs[i];
895    return mFaces[glyph.font_ix].font;
896}
897
898FontFakery Layout::getFakery(int i) const {
899    const LayoutGlyph& glyph = mGlyphs[i];
900    return mFaces[glyph.font_ix].fakery;
901}
902
903unsigned int Layout::getGlyphId(int i) const {
904    const LayoutGlyph& glyph = mGlyphs[i];
905    return glyph.glyph_id;
906}
907
908float Layout::getX(int i) const {
909    const LayoutGlyph& glyph = mGlyphs[i];
910    return glyph.x;
911}
912
913float Layout::getY(int i) const {
914    const LayoutGlyph& glyph = mGlyphs[i];
915    return glyph.y;
916}
917
918float Layout::getAdvance() const {
919    return mAdvance;
920}
921
922void Layout::getAdvances(float* advances) {
923    memcpy(advances, &mAdvances[0], mAdvances.size() * sizeof(float));
924}
925
926void Layout::getBounds(MinikinRect* bounds) {
927    bounds->set(mBounds);
928}
929
930void Layout::purgeCaches() {
931    AutoMutex _l(gMinikinLock);
932    LayoutCache& layoutCache = LayoutEngine::getInstance().layoutCache;
933    layoutCache.clear();
934    purgeHbFaceCacheLocked();
935}
936
937}  // namespace android
938