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