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