Layout.cpp revision 67ea671fe421d0e4642caef619ec39ec86bdcaef
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    int32_t 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(FakedFont face, LayoutContext* ctx) {
332    unsigned int ix;
333    for (ix = 0; ix < mFaces.size(); ix++) {
334        if (mFaces[ix].font == face.font) {
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.font, &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
488static void clearHbFonts(LayoutContext* ctx) {
489    for (size_t i = 0; i < ctx->hbFonts.size(); i++) {
490        hb_font_destroy(ctx->hbFonts[i]);
491    }
492    ctx->hbFonts.clear();
493}
494
495void Layout::doLayout(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
496        const string& css) {
497    AutoMutex _l(gMinikinLock);
498    LayoutContext ctx;
499
500    ctx.props.parse(css);
501    ctx.style = styleFromCss(ctx.props);
502
503    ctx.paint.size = ctx.props.value(fontSize).getDoubleValue();
504    ctx.paint.scaleX = ctx.props.hasTag(fontScaleX)
505            ? ctx.props.value(fontScaleX).getDoubleValue() : 1;
506    ctx.paint.skewX = ctx.props.hasTag(fontSkewX)
507            ? ctx.props.value(fontSkewX).getDoubleValue() : 0;
508    ctx.paint.paintFlags = ctx.props.hasTag(paintFlags)
509            ? ctx.props.value(paintFlags).getUintValue() : 0;
510    int bidiFlags = ctx.props.hasTag(minikinBidi) ? ctx.props.value(minikinBidi).getIntValue() : 0;
511    bool isRtl = (bidiFlags & kDirection_Mask) != 0;
512    bool doSingleRun = true;
513
514    mGlyphs.clear();
515    mFaces.clear();
516    mBounds.setEmpty();
517    mAdvances.clear();
518    mAdvances.resize(count, 0);
519    mAdvance = 0;
520    if (!(bidiFlags == kBidi_Force_LTR || bidiFlags == kBidi_Force_RTL)) {
521        UBiDi* bidi = ubidi_open();
522        if (bidi) {
523            UErrorCode status = U_ZERO_ERROR;
524            UBiDiLevel bidiReq = bidiFlags;
525            if (bidiFlags == kBidi_Default_LTR) {
526                bidiReq = UBIDI_DEFAULT_LTR;
527            } else if (bidiFlags == kBidi_Default_RTL) {
528                bidiReq = UBIDI_DEFAULT_RTL;
529            }
530            ubidi_setPara(bidi, buf, bufSize, bidiReq, NULL, &status);
531            if (U_SUCCESS(status)) {
532                int paraDir = ubidi_getParaLevel(bidi) & kDirection_Mask;
533                ssize_t rc = ubidi_countRuns(bidi, &status);
534                if (!U_SUCCESS(status) || rc < 0) {
535                    ALOGW("error counting bidi runs, status = %d", status);
536                }
537                if (!U_SUCCESS(status) || rc <= 1) {
538                    isRtl = (paraDir == kBidi_RTL);
539                } else {
540                    doSingleRun = false;
541                    // iterate through runs
542                    for (ssize_t i = 0; i < (ssize_t)rc; i++) {
543                        int32_t startRun = -1;
544                        int32_t lengthRun = -1;
545                        UBiDiDirection runDir = ubidi_getVisualRun(bidi, i, &startRun, &lengthRun);
546                        if (startRun == -1 || lengthRun == -1) {
547                            ALOGE("invalid visual run");
548                            // skip the invalid run
549                            continue;
550                        }
551                        int32_t endRun = std::min(startRun + lengthRun, int32_t(start + count));
552                        startRun = std::max(startRun, int32_t(start));
553                        lengthRun = endRun - startRun;
554                        if (lengthRun > 0) {
555                            isRtl = (runDir == UBIDI_RTL);
556                            doLayoutRunCached(buf, startRun, lengthRun, bufSize, isRtl, &ctx,
557                                start);
558                        }
559                    }
560                }
561            } else {
562                ALOGE("error calling ubidi_setPara, status = %d", status);
563            }
564            ubidi_close(bidi);
565        } else {
566            ALOGE("error creating bidi object");
567        }
568    }
569    if (doSingleRun) {
570        doLayoutRunCached(buf, start, count, bufSize, isRtl, &ctx, start);
571    }
572    clearHbFonts(&ctx);
573}
574
575void Layout::doLayoutRunCached(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
576        bool isRtl, LayoutContext* ctx, size_t dstStart) {
577    if (!isRtl) {
578        // left to right
579        size_t wordstart = start == bufSize ? start : getPrevWordBreak(buf, start + 1);
580        size_t wordend;
581        for (size_t iter = start; iter < start + count; iter = wordend) {
582            wordend = getNextWordBreak(buf, iter, bufSize);
583            size_t wordcount = std::min(start + count, wordend) - iter;
584            doLayoutWord(buf + wordstart, iter - wordstart, wordcount, wordend - wordstart,
585                    isRtl, ctx, iter - dstStart);
586            wordstart = wordend;
587        }
588    } else {
589        // right to left
590        size_t wordstart;
591        size_t end = start + count;
592        size_t wordend = end == 0 ? 0 : getNextWordBreak(buf, end - 1, bufSize);
593        for (size_t iter = end; iter > start; iter = wordstart) {
594            wordstart = getPrevWordBreak(buf, iter);
595            size_t bufStart = std::max(start, wordstart);
596            doLayoutWord(buf + wordstart, bufStart - wordstart, iter - bufStart,
597                    wordend - wordstart, isRtl, ctx, bufStart - dstStart);
598            wordend = wordstart;
599        }
600    }
601}
602
603void Layout::doLayoutWord(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
604        bool isRtl, LayoutContext* ctx, size_t bufStart) {
605    LayoutCache& cache = LayoutEngine::getInstance().layoutCache;
606    LayoutCacheKey key(mCollection, ctx->paint, ctx->style, buf, start, count, bufSize, isRtl);
607    Layout* value = cache.mCache.get(key);
608    if (value == NULL) {
609        value = new Layout();
610        value->setFontCollection(mCollection);
611        value->mAdvances.resize(count, 0);
612        clearHbFonts(ctx);
613        // Note: we do the layout from the copy stored in the key, in case a
614        // badly-behaved client is mutating the buffer in a separate thread.
615        value->doLayoutRun(key.textBuf(), start, count, bufSize, isRtl, ctx);
616    }
617    appendLayout(value, bufStart);
618    cache.mCache.put(key, value);
619}
620
621static void addFeatures(vector<hb_feature_t>* features) {
622    // hardcoded features, to be repaced with more flexible configuration
623    static hb_feature_t palt = { HB_TAG('p', 'a', 'l', 't'), 1, 0, ~0u };
624
625    // Don't enable "palt" for now, pending implementation of more of the
626    // W3C Japanese layout recommendations. See:
627    // http://www.w3.org/TR/2012/NOTE-jlreq-20120403/
628#if 0
629    features->push_back(palt);
630#endif
631}
632
633void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
634        bool isRtl, LayoutContext* ctx) {
635    hb_buffer_t* buffer = LayoutEngine::getInstance().hbBuffer;
636    vector<FontCollection::Run> items;
637    mCollection->itemize(buf + start, count, ctx->style, &items);
638    if (isRtl) {
639        std::reverse(items.begin(), items.end());
640    }
641
642    vector<hb_feature_t> features;
643    addFeatures(&features);
644
645    float x = mAdvance;
646    float y = 0;
647    for (size_t run_ix = 0; run_ix < items.size(); run_ix++) {
648        FontCollection::Run &run = items[run_ix];
649        if (run.fakedFont.font == NULL) {
650            ALOGE("no font for run starting u+%04x length %d", buf[run.start], run.end - run.start);
651            continue;
652        }
653        int font_ix = findFace(run.fakedFont, ctx);
654        ctx->paint.font = mFaces[font_ix].font;
655        ctx->paint.fakery = mFaces[font_ix].fakery;
656        hb_font_t* hbFont = ctx->hbFonts[font_ix];
657#ifdef VERBOSE
658        std::cout << "Run " << run_ix << ", font " << font_ix <<
659            " [" << run.start << ":" << run.end << "]" << std::endl;
660#endif
661        double size = ctx->paint.size;
662        double scaleX = ctx->paint.scaleX;
663        hb_font_set_ppem(hbFont, size * scaleX, size);
664        hb_font_set_scale(hbFont, HBFloatToFixed(size * scaleX), HBFloatToFixed(size));
665
666        // TODO: if there are multiple scripts within a font in an RTL run,
667        // we need to reorder those runs. This is unlikely with our current
668        // font stack, but should be done for correctness.
669        ssize_t srunend;
670        for (ssize_t srunstart = run.start; srunstart < run.end; srunstart = srunend) {
671            srunend = srunstart;
672            hb_script_t script = getScriptRun(buf + start, run.end, &srunend);
673
674            hb_buffer_reset(buffer);
675            hb_buffer_set_script(buffer, script);
676            hb_buffer_set_direction(buffer, isRtl? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
677            if (ctx->props.hasTag(cssLang)) {
678                string lang = ctx->props.value(cssLang).getStringValue();
679                hb_buffer_set_language(buffer, hb_language_from_string(lang.c_str(), -1));
680            }
681            hb_buffer_add_utf16(buffer, buf, bufSize, srunstart + start, srunend - srunstart);
682            hb_shape(hbFont, buffer, features.empty() ? NULL : &features[0], features.size());
683            unsigned int numGlyphs;
684            hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, &numGlyphs);
685            hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buffer, NULL);
686            for (unsigned int i = 0; i < numGlyphs; i++) {
687    #ifdef VERBOSE
688                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 <<
689                ": " << HBFixedToFloat(positions[i].x_advance) << "; " << positions[i].x_offset << ", " << positions[i].y_offset << std::endl;
690    #endif
691                hb_codepoint_t glyph_ix = info[i].codepoint;
692                float xoff = HBFixedToFloat(positions[i].x_offset);
693                float yoff = -HBFixedToFloat(positions[i].y_offset);
694                xoff += yoff * ctx->paint.skewX;
695                LayoutGlyph glyph = {font_ix, glyph_ix, x + xoff, y + yoff};
696                mGlyphs.push_back(glyph);
697                float xAdvance = HBFixedToFloat(positions[i].x_advance);
698                MinikinRect glyphBounds;
699                ctx->paint.font->GetBounds(&glyphBounds, glyph_ix, ctx->paint);
700                glyphBounds.offset(x + xoff, y + yoff);
701                mBounds.join(glyphBounds);
702                size_t cluster = info[i].cluster - start;
703                mAdvances[cluster] += xAdvance;
704                x += xAdvance;
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
763void Layout::setProperties(const string& css) {
764    mCssString = css;
765}
766
767size_t Layout::nGlyphs() const {
768    return mGlyphs.size();
769}
770
771MinikinFont* Layout::getFont(int i) const {
772    const LayoutGlyph& glyph = mGlyphs[i];
773    return mFaces[glyph.font_ix].font;
774}
775
776FontFakery Layout::getFakery(int i) const {
777    const LayoutGlyph& glyph = mGlyphs[i];
778    return mFaces[glyph.font_ix].fakery;
779}
780
781unsigned int Layout::getGlyphId(int i) const {
782    const LayoutGlyph& glyph = mGlyphs[i];
783    return glyph.glyph_id;
784}
785
786float Layout::getX(int i) const {
787    const LayoutGlyph& glyph = mGlyphs[i];
788    return glyph.x;
789}
790
791float Layout::getY(int i) const {
792    const LayoutGlyph& glyph = mGlyphs[i];
793    return glyph.y;
794}
795
796float Layout::getAdvance() const {
797    return mAdvance;
798}
799
800void Layout::getAdvances(float* advances) {
801    memcpy(advances, &mAdvances[0], mAdvances.size() * sizeof(float));
802}
803
804void Layout::getBounds(MinikinRect* bounds) {
805    bounds->set(mBounds);
806}
807
808void Layout::purgeCaches() {
809    AutoMutex _l(gMinikinLock);
810    LayoutCache& layoutCache = LayoutEngine::getInstance().layoutCache;
811    layoutCache.mCache.clear();
812    HbFaceCache& hbCache = LayoutEngine::getInstance().hbFaceCache;
813    hbCache.mCache.clear();
814}
815
816}  // namespace android
817