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