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