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