Layout.cpp revision b4c799180458fc37b96ee43ef9111f64e0cc99f7
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, hb_codepoint_t glyph, void* userData)
280{
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, hb_codepoint_t glyph, hb_position_t* x, hb_position_t* y, void* userData)
288{
289    // Just return true, following the way that Harfbuzz-FreeType
290    // implementation does.
291    return true;
292}
293
294hb_font_funcs_t* getHbFontFuncs() {
295    static hb_font_funcs_t* hbFontFuncs = 0;
296
297    if (hbFontFuncs == 0) {
298        hbFontFuncs = hb_font_funcs_create();
299        hb_font_funcs_set_glyph_h_advance_func(hbFontFuncs, harfbuzzGetGlyphHorizontalAdvance, 0, 0);
300        hb_font_funcs_set_glyph_h_origin_func(hbFontFuncs, harfbuzzGetGlyphHorizontalOrigin, 0, 0);
301        hb_font_funcs_make_immutable(hbFontFuncs);
302    }
303    return hbFontFuncs;
304}
305
306static hb_font_t* create_hb_font(MinikinFont* minikinFont, MinikinPaint* minikinPaint) {
307    hb_face_t* face = getHbFaceLocked(minikinFont);
308    hb_font_t* parent_font = hb_font_create(face);
309    hb_ot_font_set_funcs(parent_font);
310
311    unsigned int upem = hb_face_get_upem(face);
312    hb_font_set_scale(parent_font, upem, upem);
313
314    hb_font_t* font = hb_font_create_sub_font(parent_font);
315    hb_font_destroy(parent_font);
316
317    hb_font_set_funcs(font, getHbFontFuncs(), minikinPaint, 0);
318    return font;
319}
320
321static float HBFixedToFloat(hb_position_t v)
322{
323    return scalbnf (v, -8);
324}
325
326static hb_position_t HBFloatToFixed(float v)
327{
328    return scalbnf (v, +8);
329}
330
331void Layout::dump() const {
332    for (size_t i = 0; i < mGlyphs.size(); i++) {
333        const LayoutGlyph& glyph = mGlyphs[i];
334        std::cout << glyph.glyph_id << ": " << glyph.x << ", " << glyph.y << std::endl;
335    }
336}
337
338int Layout::findFace(FakedFont face, LayoutContext* ctx) {
339    unsigned int ix;
340    for (ix = 0; ix < mFaces.size(); ix++) {
341        if (mFaces[ix].font == face.font) {
342            return ix;
343        }
344    }
345    mFaces.push_back(face);
346    // Note: ctx == NULL means we're copying from the cache, no need to create
347    // corresponding hb_font object.
348    if (ctx != NULL) {
349        hb_font_t* font = create_hb_font(face.font, &ctx->paint);
350        ctx->hbFonts.push_back(font);
351    }
352    return ix;
353}
354
355static hb_script_t codePointToScript(hb_codepoint_t codepoint) {
356    static hb_unicode_funcs_t* u = 0;
357    if (!u) {
358        u = LayoutEngine::getInstance().unicodeFunctions;
359    }
360    return hb_unicode_script(u, codepoint);
361}
362
363static hb_codepoint_t decodeUtf16(const uint16_t* chars, size_t len, ssize_t* iter) {
364    const uint16_t v = chars[(*iter)++];
365    // test whether v in (0xd800..0xdfff), lead or trail surrogate
366    if ((v & 0xf800) == 0xd800) {
367        // test whether v in (0xd800..0xdbff), lead surrogate
368        if (size_t(*iter) < len && (v & 0xfc00) == 0xd800) {
369            const uint16_t v2 = chars[(*iter)++];
370            // test whether v2 in (0xdc00..0xdfff), trail surrogate
371            if ((v2 & 0xfc00) == 0xdc00) {
372                // (0xd800 0xdc00) in utf-16 maps to 0x10000 in ucs-32
373                const hb_codepoint_t delta = (0xd800 << 10) + 0xdc00 - 0x10000;
374                return (((hb_codepoint_t)v) << 10) + v2 - delta;
375            }
376            (*iter) -= 1;
377            return 0xFFFDu;
378        } else {
379            return 0xFFFDu;
380        }
381    } else {
382        return v;
383    }
384}
385
386static hb_script_t getScriptRun(const uint16_t* chars, size_t len, ssize_t* iter) {
387    if (size_t(*iter) == len) {
388        return HB_SCRIPT_UNKNOWN;
389    }
390    uint32_t cp = decodeUtf16(chars, len, iter);
391    hb_script_t current_script = codePointToScript(cp);
392    for (;;) {
393        if (size_t(*iter) == len)
394            break;
395        const ssize_t prev_iter = *iter;
396        cp = decodeUtf16(chars, len, iter);
397        const hb_script_t script = codePointToScript(cp);
398        if (script != current_script) {
399            if (current_script == HB_SCRIPT_INHERITED ||
400                current_script == HB_SCRIPT_COMMON) {
401                current_script = script;
402            } else if (script == HB_SCRIPT_INHERITED ||
403                script == HB_SCRIPT_COMMON) {
404                continue;
405            } else {
406                *iter = prev_iter;
407                break;
408            }
409        }
410    }
411    if (current_script == HB_SCRIPT_INHERITED) {
412        current_script = HB_SCRIPT_COMMON;
413    }
414
415    return current_script;
416}
417
418/**
419 * Disable certain scripts (mostly those with cursive connection) from having letterspacing
420 * applied. See https://github.com/behdad/harfbuzz/issues/64 for more details.
421 */
422static bool isScriptOkForLetterspacing(hb_script_t script) {
423    return !(
424            script == HB_SCRIPT_ARABIC ||
425            script == HB_SCRIPT_NKO ||
426            script == HB_SCRIPT_PSALTER_PAHLAVI ||
427            script == HB_SCRIPT_MANDAIC ||
428            script == HB_SCRIPT_MONGOLIAN ||
429            script == HB_SCRIPT_PHAGS_PA ||
430            script == HB_SCRIPT_DEVANAGARI ||
431            script == HB_SCRIPT_BENGALI ||
432            script == HB_SCRIPT_GURMUKHI ||
433            script == HB_SCRIPT_MODI ||
434            script == HB_SCRIPT_SHARADA ||
435            script == HB_SCRIPT_SYLOTI_NAGRI ||
436            script == HB_SCRIPT_TIRHUTA ||
437            script == HB_SCRIPT_OGHAM
438            );
439}
440
441class BidiText {
442public:
443    class Iter {
444    public:
445        struct RunInfo {
446            int32_t mRunStart;
447            int32_t mRunLength;
448            bool mIsRtl;
449        };
450
451        Iter(UBiDi* bidi, size_t start, size_t end, size_t runIndex, size_t runCount, bool isRtl);
452
453        bool operator!= (const Iter& other) const {
454            return mIsEnd != other.mIsEnd || mNextRunIndex != other.mNextRunIndex
455                    || mBidi != other.mBidi;
456        }
457
458        const RunInfo& operator* () const {
459            return mRunInfo;
460        }
461
462        const Iter& operator++ () {
463            updateRunInfo();
464            return *this;
465        }
466
467    private:
468        UBiDi* const mBidi;
469        bool mIsEnd;
470        size_t mNextRunIndex;
471        const size_t mRunCount;
472        const int32_t mStart;
473        const int32_t mEnd;
474        RunInfo mRunInfo;
475
476        void updateRunInfo();
477    };
478
479    BidiText(const uint16_t* buf, size_t start, size_t count, size_t bufSize, int bidiFlags);
480
481    ~BidiText() {
482        if (mBidi) {
483            ubidi_close(mBidi);
484        }
485    }
486
487    Iter begin () const {
488        return Iter(mBidi, mStart, mEnd, 0, mRunCount, mIsRtl);
489    }
490
491    Iter end() const {
492        return Iter(mBidi, mStart, mEnd, mRunCount, mRunCount, mIsRtl);
493    }
494
495private:
496    const size_t mStart;
497    const size_t mEnd;
498    const size_t mBufSize;
499    UBiDi* mBidi;
500    size_t mRunCount;
501    bool mIsRtl;
502
503    DISALLOW_COPY_AND_ASSIGN(BidiText);
504};
505
506BidiText::Iter::Iter(UBiDi* bidi, size_t start, size_t end, size_t runIndex, size_t runCount,
507        bool isRtl)
508    : mBidi(bidi), mIsEnd(runIndex == runCount), mNextRunIndex(runIndex), mRunCount(runCount),
509      mStart(start), mEnd(end), mRunInfo() {
510    if (mRunCount == 1) {
511        mRunInfo.mRunStart = start;
512        mRunInfo.mRunLength = end - start;
513        mRunInfo.mIsRtl = isRtl;
514        mNextRunIndex = mRunCount;
515        return;
516    }
517    updateRunInfo();
518}
519
520void BidiText::Iter::updateRunInfo() {
521    if (mNextRunIndex == mRunCount) {
522        // All runs have been iterated.
523        mIsEnd = true;
524        return;
525    }
526    int32_t startRun = -1;
527    int32_t lengthRun = -1;
528    const UBiDiDirection runDir = ubidi_getVisualRun(mBidi, mNextRunIndex, &startRun, &lengthRun);
529    mNextRunIndex++;
530    if (startRun == -1 || lengthRun == -1) {
531        ALOGE("invalid visual run");
532        // skip the invalid run.
533        updateRunInfo();
534        return;
535    }
536    const int32_t runEnd = std::min(startRun + lengthRun, mEnd);
537    mRunInfo.mRunStart = std::max(startRun, mStart);
538    mRunInfo.mRunLength = runEnd - mRunInfo.mRunStart;
539    if (mRunInfo.mRunLength <= 0) {
540        // skip the empty run.
541        updateRunInfo();
542        return;
543    }
544    mRunInfo.mIsRtl = (runDir == UBIDI_RTL);
545}
546
547BidiText::BidiText(const uint16_t* buf, size_t start, size_t count, size_t bufSize, int bidiFlags)
548    : mStart(start), mEnd(start + count), mBufSize(bufSize), mBidi(NULL), mRunCount(1),
549      mIsRtl((bidiFlags & kDirection_Mask) != 0) {
550    if (bidiFlags == kBidi_Force_LTR || bidiFlags == kBidi_Force_RTL) {
551        // force single run.
552        return;
553    }
554    mBidi = ubidi_open();
555    if (!mBidi) {
556        ALOGE("error creating bidi object");
557        return;
558    }
559    UErrorCode status = U_ZERO_ERROR;
560    UBiDiLevel bidiReq = bidiFlags;
561    if (bidiFlags == kBidi_Default_LTR) {
562        bidiReq = UBIDI_DEFAULT_LTR;
563    } else if (bidiFlags == kBidi_Default_RTL) {
564        bidiReq = UBIDI_DEFAULT_RTL;
565    }
566    ubidi_setPara(mBidi, buf, mBufSize, bidiReq, NULL, &status);
567    if (!U_SUCCESS(status)) {
568        ALOGE("error calling ubidi_setPara, status = %d", status);
569        return;
570    }
571    const int paraDir = ubidi_getParaLevel(mBidi) & kDirection_Mask;
572    const ssize_t rc = ubidi_countRuns(mBidi, &status);
573    if (!U_SUCCESS(status) || rc < 0) {
574        ALOGW("error counting bidi runs, status = %d", status);
575    }
576    if (!U_SUCCESS(status) || rc <= 1) {
577        mIsRtl = (paraDir == kBidi_RTL);
578        return;
579    }
580    mRunCount = rc;
581}
582
583void Layout::doLayout(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
584        int bidiFlags, const FontStyle &style, const MinikinPaint &paint) {
585    AutoMutex _l(gMinikinLock);
586
587    LayoutContext ctx;
588    ctx.style = style;
589    ctx.paint = paint;
590
591    reset();
592    mAdvances.resize(count, 0);
593
594    for (const BidiText::Iter::RunInfo& runInfo : BidiText(buf, start, count, bufSize, bidiFlags)) {
595        doLayoutRunCached(buf, runInfo.mRunStart, runInfo.mRunLength, bufSize, runInfo.mIsRtl, &ctx,
596                start);
597    }
598    ctx.clearHbFonts();
599    mCollection->purgeFontFamilyHbFontCache();
600}
601
602void Layout::doLayoutRunCached(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
603        bool isRtl, LayoutContext* ctx, size_t dstStart) {
604    HyphenEdit hyphen = ctx->paint.hyphenEdit;
605    if (!isRtl) {
606        // left to right
607        size_t wordstart =
608                start == bufSize ? start : getPrevWordBreakForCache(buf, start + 1, bufSize);
609        size_t wordend;
610        for (size_t iter = start; iter < start + count; iter = wordend) {
611            wordend = getNextWordBreakForCache(buf, iter, bufSize);
612            // Only apply hyphen to the last word in the string.
613            ctx->paint.hyphenEdit = wordend >= start + count ? hyphen : HyphenEdit();
614            size_t wordcount = std::min(start + count, wordend) - iter;
615            doLayoutWord(buf + wordstart, iter - wordstart, wordcount, wordend - wordstart,
616                    isRtl, ctx, iter - dstStart);
617            wordstart = wordend;
618        }
619    } else {
620        // right to left
621        size_t wordstart;
622        size_t end = start + count;
623        size_t wordend = end == 0 ? 0 : getNextWordBreakForCache(buf, end - 1, bufSize);
624        for (size_t iter = end; iter > start; iter = wordstart) {
625            wordstart = getPrevWordBreakForCache(buf, iter, bufSize);
626            // Only apply hyphen to the last (leftmost) word in the string.
627            ctx->paint.hyphenEdit = iter == end ? hyphen : HyphenEdit();
628            size_t bufStart = std::max(start, wordstart);
629            doLayoutWord(buf + wordstart, bufStart - wordstart, iter - bufStart,
630                    wordend - wordstart, isRtl, ctx, bufStart - dstStart);
631            wordend = wordstart;
632        }
633    }
634}
635
636void Layout::doLayoutWord(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
637        bool isRtl, LayoutContext* ctx, size_t bufStart) {
638    LayoutCache& cache = LayoutEngine::getInstance().layoutCache;
639    LayoutCacheKey key(mCollection, ctx->paint, ctx->style, buf, start, count, bufSize, isRtl);
640    bool skipCache = ctx->paint.skipCache();
641    if (skipCache) {
642        Layout layout;
643        key.doLayout(&layout, ctx, mCollection);
644        appendLayout(&layout, bufStart);
645    } else {
646        Layout* layout = cache.get(key, ctx, mCollection);
647        appendLayout(layout, bufStart);
648    }
649}
650
651static void addFeatures(const string &str, vector<hb_feature_t>* features) {
652    if (!str.size())
653        return;
654
655    const char* start = str.c_str();
656    const char* end = start + str.size();
657
658    while (start < end) {
659        static hb_feature_t feature;
660        const char* p = strchr(start, ',');
661        if (!p)
662            p = end;
663        /* We do not allow setting features on ranges.  As such, reject any
664         * setting that has non-universal range. */
665        if (hb_feature_from_string (start, p - start, &feature)
666                && feature.start == 0 && feature.end == (unsigned int) -1)
667            features->push_back(feature);
668        start = p + 1;
669    }
670}
671
672void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
673        bool isRtl, LayoutContext* ctx) {
674    hb_buffer_t* buffer = LayoutEngine::getInstance().hbBuffer;
675    vector<FontCollection::Run> items;
676    mCollection->itemize(buf + start, count, ctx->style, &items);
677    if (isRtl) {
678        std::reverse(items.begin(), items.end());
679    }
680
681    vector<hb_feature_t> features;
682    // Disable default-on non-required ligature features if letter-spacing
683    // See http://dev.w3.org/csswg/css-text-3/#letter-spacing-property
684    // "When the effective spacing between two characters is not zero (due to
685    // either justification or a non-zero value of letter-spacing), user agents
686    // should not apply optional ligatures."
687    if (fabs(ctx->paint.letterSpacing) > 0.03)
688    {
689        static const hb_feature_t no_liga = { HB_TAG('l', 'i', 'g', 'a'), 0, 0, ~0u };
690        static const hb_feature_t no_clig = { HB_TAG('c', 'l', 'i', 'g'), 0, 0, ~0u };
691        features.push_back(no_liga);
692        features.push_back(no_clig);
693    }
694    addFeatures(ctx->paint.fontFeatureSettings, &features);
695
696    double size = ctx->paint.size;
697    double scaleX = ctx->paint.scaleX;
698
699    float x = mAdvance;
700    float y = 0;
701    for (size_t run_ix = 0; run_ix < items.size(); run_ix++) {
702        FontCollection::Run &run = items[run_ix];
703        if (run.fakedFont.font == NULL) {
704            ALOGE("no font for run starting u+%04x length %d", buf[run.start], run.end - run.start);
705            continue;
706        }
707        int font_ix = findFace(run.fakedFont, ctx);
708        ctx->paint.font = mFaces[font_ix].font;
709        ctx->paint.fakery = mFaces[font_ix].fakery;
710        hb_font_t* hbFont = ctx->hbFonts[font_ix];
711#ifdef VERBOSE_DEBUG
712        ALOGD("Run %u, font %d [%d:%d]", run_ix, font_ix, run.start, run.end);
713#endif
714
715        hb_font_set_ppem(hbFont, size * scaleX, size);
716        hb_font_set_scale(hbFont, HBFloatToFixed(size * scaleX), HBFloatToFixed(size));
717
718        // TODO: if there are multiple scripts within a font in an RTL run,
719        // we need to reorder those runs. This is unlikely with our current
720        // font stack, but should be done for correctness.
721        ssize_t srunend;
722        for (ssize_t srunstart = run.start; srunstart < run.end; srunstart = srunend) {
723            srunend = srunstart;
724            hb_script_t script = getScriptRun(buf + start, run.end, &srunend);
725
726            double letterSpace = 0.0;
727            double letterSpaceHalfLeft = 0.0;
728            double letterSpaceHalfRight = 0.0;
729
730            if (ctx->paint.letterSpacing != 0.0 && isScriptOkForLetterspacing(script)) {
731                letterSpace = ctx->paint.letterSpacing * size * scaleX;
732                if ((ctx->paint.paintFlags & LinearTextFlag) == 0) {
733                    letterSpace = round(letterSpace);
734                    letterSpaceHalfLeft = floor(letterSpace * 0.5);
735                } else {
736                    letterSpaceHalfLeft = letterSpace * 0.5;
737                }
738                letterSpaceHalfRight = letterSpace - letterSpaceHalfLeft;
739            }
740
741            hb_buffer_clear_contents(buffer);
742            hb_buffer_set_script(buffer, script);
743            hb_buffer_set_direction(buffer, isRtl? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
744            FontLanguage language = ctx->style.getLanguage();
745            if (language) {
746                string lang = language.getString();
747                hb_buffer_set_language(buffer, hb_language_from_string(lang.c_str(), -1));
748            }
749            hb_buffer_add_utf16(buffer, buf, bufSize, srunstart + start, srunend - srunstart);
750            if (ctx->paint.hyphenEdit.hasHyphen() && srunend > srunstart) {
751                // TODO: check whether this is really the desired semantics. It could have the
752                // effect of assigning the hyphen width to a nonspacing mark
753                unsigned int lastCluster = start + srunend - 1;
754
755                hb_codepoint_t hyphenChar = 0x2010; // HYPHEN
756                hb_codepoint_t glyph;
757                // Fallback to ASCII HYPHEN-MINUS if the font didn't have a glyph for HYPHEN. Note
758                // that we intentionally don't do anything special if the font doesn't have a
759                // HYPHEN-MINUS either, so a tofu could be shown, hinting towards something
760                // missing.
761                if (!hb_font_get_glyph(hbFont, hyphenChar, 0, &glyph)) {
762                    hyphenChar = 0x002D; // HYPHEN-MINUS
763                }
764                hb_buffer_add(buffer, hyphenChar, lastCluster);
765            }
766            hb_shape(hbFont, buffer, features.empty() ? NULL : &features[0], features.size());
767            unsigned int numGlyphs;
768            hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, &numGlyphs);
769            hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buffer, NULL);
770            if (numGlyphs)
771            {
772                mAdvances[info[0].cluster - start] += letterSpaceHalfLeft;
773                x += letterSpaceHalfLeft;
774            }
775            for (unsigned int i = 0; i < numGlyphs; i++) {
776#ifdef VERBOSE_DEBUG
777                ALOGD("%d %d %d %d",
778                        positions[i].x_advance, positions[i].y_advance,
779                        positions[i].x_offset, positions[i].y_offset);
780                ALOGD("DoLayout %u: %f; %d, %d",
781                        info[i].codepoint, HBFixedToFloat(positions[i].x_advance),
782                        positions[i].x_offset, positions[i].y_offset);
783#endif
784                if (i > 0 && info[i - 1].cluster != info[i].cluster) {
785                    mAdvances[info[i - 1].cluster - start] += letterSpaceHalfRight;
786                    mAdvances[info[i].cluster - start] += letterSpaceHalfLeft;
787                    x += letterSpace;
788                }
789
790                hb_codepoint_t glyph_ix = info[i].codepoint;
791                float xoff = HBFixedToFloat(positions[i].x_offset);
792                float yoff = -HBFixedToFloat(positions[i].y_offset);
793                xoff += yoff * ctx->paint.skewX;
794                LayoutGlyph glyph = {font_ix, glyph_ix, x + xoff, y + yoff};
795                mGlyphs.push_back(glyph);
796                float xAdvance = HBFixedToFloat(positions[i].x_advance);
797                if ((ctx->paint.paintFlags & LinearTextFlag) == 0) {
798                    xAdvance = roundf(xAdvance);
799                }
800                MinikinRect glyphBounds;
801                ctx->paint.font->GetBounds(&glyphBounds, glyph_ix, ctx->paint);
802                glyphBounds.offset(x + xoff, y + yoff);
803                mBounds.join(glyphBounds);
804                if (info[i].cluster - start < count) {
805                    mAdvances[info[i].cluster - start] += xAdvance;
806                } else {
807                    ALOGE("cluster %d (start %d) out of bounds of count %d",
808                        info[i].cluster - start, start, count);
809                }
810                x += xAdvance;
811            }
812            if (numGlyphs)
813            {
814                mAdvances[info[numGlyphs - 1].cluster - start] += letterSpaceHalfRight;
815                x += letterSpaceHalfRight;
816            }
817        }
818    }
819    mAdvance = x;
820}
821
822void Layout::appendLayout(Layout* src, size_t start) {
823    int fontMapStack[16];
824    int* fontMap;
825    if (src->mFaces.size() < sizeof(fontMapStack) / sizeof(fontMapStack[0])) {
826        fontMap = fontMapStack;
827    } else {
828        fontMap = new int[src->mFaces.size()];
829    }
830    for (size_t i = 0; i < src->mFaces.size(); i++) {
831        int font_ix = findFace(src->mFaces[i], NULL);
832        fontMap[i] = font_ix;
833    }
834    int x0 = mAdvance;
835    for (size_t i = 0; i < src->mGlyphs.size(); i++) {
836        LayoutGlyph& srcGlyph = src->mGlyphs[i];
837        int font_ix = fontMap[srcGlyph.font_ix];
838        unsigned int glyph_id = srcGlyph.glyph_id;
839        float x = x0 + srcGlyph.x;
840        float y = srcGlyph.y;
841        LayoutGlyph glyph = {font_ix, glyph_id, x, y};
842        mGlyphs.push_back(glyph);
843    }
844    for (size_t i = 0; i < src->mAdvances.size(); i++) {
845        mAdvances[i + start] = src->mAdvances[i];
846    }
847    MinikinRect srcBounds(src->mBounds);
848    srcBounds.offset(x0, 0);
849    mBounds.join(srcBounds);
850    mAdvance += src->mAdvance;
851
852    if (fontMap != fontMapStack) {
853        delete[] fontMap;
854    }
855}
856
857void Layout::draw(minikin::Bitmap* surface, int x0, int y0, float size) const {
858    /*
859    TODO: redo as MinikinPaint settings
860    if (mProps.hasTag(minikinHinting)) {
861        int hintflags = mProps.value(minikinHinting).getIntValue();
862        if (hintflags & 1) load_flags |= FT_LOAD_NO_HINTING;
863        if (hintflags & 2) load_flags |= FT_LOAD_NO_AUTOHINT;
864    }
865    */
866    for (size_t i = 0; i < mGlyphs.size(); i++) {
867        const LayoutGlyph& glyph = mGlyphs[i];
868        MinikinFont* mf = mFaces[glyph.font_ix].font;
869        MinikinFontFreeType* face = static_cast<MinikinFontFreeType*>(mf);
870        GlyphBitmap glyphBitmap;
871        MinikinPaint paint;
872        paint.size = size;
873        bool ok = face->Render(glyph.glyph_id, paint, &glyphBitmap);
874#ifdef VERBOSE_DEBUG
875        ALOGD("glyphBitmap.width=%d, glyphBitmap.height=%d (%d, %d) x=%f, y=%f, ok=%d",
876            glyphBitmap.width, glyphBitmap.height, glyphBitmap.left, glyphBitmap.top, glyph.x, glyph.y, ok);
877#endif
878        if (ok) {
879            surface->drawGlyph(glyphBitmap,
880                x0 + int(floor(glyph.x + 0.5)), y0 + int(floor(glyph.y + 0.5)));
881        }
882    }
883}
884
885size_t Layout::nGlyphs() const {
886    return mGlyphs.size();
887}
888
889MinikinFont* Layout::getFont(int i) const {
890    const LayoutGlyph& glyph = mGlyphs[i];
891    return mFaces[glyph.font_ix].font;
892}
893
894FontFakery Layout::getFakery(int i) const {
895    const LayoutGlyph& glyph = mGlyphs[i];
896    return mFaces[glyph.font_ix].fakery;
897}
898
899unsigned int Layout::getGlyphId(int i) const {
900    const LayoutGlyph& glyph = mGlyphs[i];
901    return glyph.glyph_id;
902}
903
904float Layout::getX(int i) const {
905    const LayoutGlyph& glyph = mGlyphs[i];
906    return glyph.x;
907}
908
909float Layout::getY(int i) const {
910    const LayoutGlyph& glyph = mGlyphs[i];
911    return glyph.y;
912}
913
914float Layout::getAdvance() const {
915    return mAdvance;
916}
917
918void Layout::getAdvances(float* advances) {
919    memcpy(advances, &mAdvances[0], mAdvances.size() * sizeof(float));
920}
921
922void Layout::getBounds(MinikinRect* bounds) {
923    bounds->set(mBounds);
924}
925
926void Layout::purgeCaches() {
927    AutoMutex _l(gMinikinLock);
928    LayoutCache& layoutCache = LayoutEngine::getInstance().layoutCache;
929    layoutCache.clear();
930    purgeHbFaceCacheLocked();
931}
932
933}  // namespace android
934