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