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