Layout.cpp revision 338de7c42303c9710d37242fac8727c36caee174
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// TODO: the actual initialization is deferred, maybe make this explicit
271void Layout::init() {
272}
273
274void Layout::setFontCollection(const FontCollection* collection) {
275    mCollection = collection;
276}
277
278hb_blob_t* referenceTable(hb_face_t* face, hb_tag_t tag, void* userData)  {
279    MinikinFont* font = reinterpret_cast<MinikinFont*>(userData);
280    size_t length = 0;
281    bool ok = font->GetTable(tag, NULL, &length);
282    if (!ok) {
283        return 0;
284    }
285    char* buffer = reinterpret_cast<char*>(malloc(length));
286    if (!buffer) {
287        return 0;
288    }
289    ok = font->GetTable(tag, reinterpret_cast<uint8_t*>(buffer), &length);
290    printf("referenceTable %c%c%c%c length=%d %d\n",
291        (tag >>24) & 0xff, (tag>>16)&0xff, (tag>>8)&0xff, tag&0xff, length, ok);
292    if (!ok) {
293        free(buffer);
294        return 0;
295    }
296    return hb_blob_create(const_cast<char*>(buffer), length,
297        HB_MEMORY_MODE_WRITABLE, buffer, free);
298}
299
300static hb_bool_t harfbuzzGetGlyph(hb_font_t* hbFont, void* fontData, hb_codepoint_t unicode, hb_codepoint_t variationSelector, hb_codepoint_t* glyph, void* userData)
301{
302    MinikinPaint* paint = reinterpret_cast<MinikinPaint*>(fontData);
303    MinikinFont* font = paint->font;
304    uint32_t glyph_id;
305    bool ok = font->GetGlyph(unicode, &glyph_id);
306    if (ok) {
307        *glyph = glyph_id;
308    }
309    return ok;
310}
311
312static hb_position_t harfbuzzGetGlyphHorizontalAdvance(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, void* userData)
313{
314    MinikinPaint* paint = reinterpret_cast<MinikinPaint*>(fontData);
315    MinikinFont* font = paint->font;
316    float advance = font->GetHorizontalAdvance(glyph, *paint);
317    return 256 * advance + 0.5;
318}
319
320static hb_bool_t harfbuzzGetGlyphHorizontalOrigin(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_position_t* x, hb_position_t* y, void* userData)
321{
322    // Just return true, following the way that Harfbuzz-FreeType
323    // implementation does.
324    return true;
325}
326
327hb_font_funcs_t* getHbFontFuncs() {
328    static hb_font_funcs_t* hbFontFuncs = 0;
329
330    if (hbFontFuncs == 0) {
331        hbFontFuncs = hb_font_funcs_create();
332        hb_font_funcs_set_glyph_func(hbFontFuncs, harfbuzzGetGlyph, 0, 0);
333        hb_font_funcs_set_glyph_h_advance_func(hbFontFuncs, harfbuzzGetGlyphHorizontalAdvance, 0, 0);
334        hb_font_funcs_set_glyph_h_origin_func(hbFontFuncs, harfbuzzGetGlyphHorizontalOrigin, 0, 0);
335        hb_font_funcs_make_immutable(hbFontFuncs);
336    }
337    return hbFontFuncs;
338}
339
340static hb_face_t* getHbFace(MinikinFont* minikinFont) {
341    HbFaceCache& cache = LayoutEngine::getInstance().hbFaceCache;
342    int32_t fontId = minikinFont->GetUniqueId();
343    hb_face_t* face = cache.mCache.get(fontId);
344    if (face == NULL) {
345        face = hb_face_create_for_tables(referenceTable, minikinFont, NULL);
346        cache.mCache.put(fontId, face);
347    }
348    return face;
349}
350
351static hb_font_t* create_hb_font(MinikinFont* minikinFont, MinikinPaint* minikinPaint) {
352    hb_face_t* face = getHbFace(minikinFont);
353    hb_font_t* font = hb_font_create(face);
354    hb_font_set_funcs(font, getHbFontFuncs(), minikinPaint, 0);
355    return font;
356}
357
358static float HBFixedToFloat(hb_position_t v)
359{
360    return scalbnf (v, -8);
361}
362
363static hb_position_t HBFloatToFixed(float v)
364{
365    return scalbnf (v, +8);
366}
367
368void Layout::dump() const {
369    for (size_t i = 0; i < mGlyphs.size(); i++) {
370        const LayoutGlyph& glyph = mGlyphs[i];
371        std::cout << glyph.glyph_id << ": " << glyph.x << ", " << glyph.y << std::endl;
372    }
373}
374
375int Layout::findFace(FakedFont face, LayoutContext* ctx) {
376    unsigned int ix;
377    for (ix = 0; ix < mFaces.size(); ix++) {
378        if (mFaces[ix].font == face.font) {
379            return ix;
380        }
381    }
382    mFaces.push_back(face);
383    // Note: ctx == NULL means we're copying from the cache, no need to create
384    // corresponding hb_font object.
385    if (ctx != NULL) {
386        hb_font_t* font = create_hb_font(face.font, &ctx->paint);
387        ctx->hbFonts.push_back(font);
388    }
389    return ix;
390}
391
392static hb_script_t codePointToScript(hb_codepoint_t codepoint) {
393    static hb_unicode_funcs_t* u = 0;
394    if (!u) {
395        u = hb_icu_get_unicode_funcs();
396    }
397    return hb_unicode_script(u, codepoint);
398}
399
400static hb_codepoint_t decodeUtf16(const uint16_t* chars, size_t len, ssize_t* iter) {
401    const uint16_t v = chars[(*iter)++];
402    // test whether v in (0xd800..0xdfff), lead or trail surrogate
403    if ((v & 0xf800) == 0xd800) {
404        // test whether v in (0xd800..0xdbff), lead surrogate
405        if (size_t(*iter) < len && (v & 0xfc00) == 0xd800) {
406            const uint16_t v2 = chars[(*iter)++];
407            // test whether v2 in (0xdc00..0xdfff), trail surrogate
408            if ((v2 & 0xfc00) == 0xdc00) {
409                // (0xd800 0xdc00) in utf-16 maps to 0x10000 in ucs-32
410                const hb_codepoint_t delta = (0xd800 << 10) + 0xdc00 - 0x10000;
411                return (((hb_codepoint_t)v) << 10) + v2 - delta;
412            }
413            (*iter) -= 1;
414            return 0xFFFDu;
415        } else {
416            return 0xFFFDu;
417        }
418    } else {
419        return v;
420    }
421}
422
423static hb_script_t getScriptRun(const uint16_t* chars, size_t len, ssize_t* iter) {
424    if (size_t(*iter) == len) {
425        return HB_SCRIPT_UNKNOWN;
426    }
427    uint32_t cp = decodeUtf16(chars, len, iter);
428    hb_script_t current_script = codePointToScript(cp);
429    for (;;) {
430        if (size_t(*iter) == len)
431            break;
432        const ssize_t prev_iter = *iter;
433        cp = decodeUtf16(chars, len, iter);
434        const hb_script_t script = codePointToScript(cp);
435        if (script != current_script) {
436            if (current_script == HB_SCRIPT_INHERITED ||
437                current_script == HB_SCRIPT_COMMON) {
438                current_script = script;
439            } else if (script == HB_SCRIPT_INHERITED ||
440                script == HB_SCRIPT_COMMON) {
441                continue;
442            } else {
443                *iter = prev_iter;
444                break;
445            }
446        }
447    }
448    if (current_script == HB_SCRIPT_INHERITED) {
449        current_script = HB_SCRIPT_COMMON;
450    }
451
452    return current_script;
453}
454
455/**
456 * For the purpose of layout, a word break is a boundary with no
457 * kerning or complex script processing. This is necessarily a
458 * heuristic, but should be accurate most of the time.
459 */
460static bool isWordBreak(int c) {
461    if (c == ' ' || (c >= 0x2000 && c <= 0x200a) || c == 0x3000) {
462        // spaces
463        return true;
464    }
465    if ((c >= 0x3400 && c <= 0x9fff)) {
466        // CJK ideographs (and yijing hexagram symbols)
467        return true;
468    }
469    // Note: kana is not included, as sophisticated fonts may kern kana
470    return false;
471}
472
473/**
474 * Return offset of previous word break. It is either < offset or == 0.
475 */
476static size_t getPrevWordBreak(const uint16_t* chars, size_t offset) {
477    if (offset == 0) return 0;
478    if (isWordBreak(chars[offset - 1])) {
479        return offset - 1;
480    }
481    for (size_t i = offset - 1; i > 0; i--) {
482        if (isWordBreak(chars[i - 1])) {
483            return i;
484        }
485    }
486    return 0;
487}
488
489/**
490 * Return offset of next word break. It is either > offset or == len.
491 */
492static size_t getNextWordBreak(const uint16_t* chars, size_t offset, size_t len) {
493    if (offset >= len) return len;
494    if (isWordBreak(chars[offset])) {
495        return offset + 1;
496    }
497    for (size_t i = offset + 1; i < len; i++) {
498        if (isWordBreak(chars[i])) {
499            return i;
500        }
501    }
502    return len;
503}
504
505void Layout::doLayout(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
506        int bidiFlags, const FontStyle &style, const MinikinPaint &paint) {
507    AutoMutex _l(gMinikinLock);
508
509    LayoutContext ctx;
510    ctx.style = style;
511    ctx.paint = paint;
512
513    bool isRtl = (bidiFlags & kDirection_Mask) != 0;
514    bool doSingleRun = true;
515
516    mGlyphs.clear();
517    mFaces.clear();
518    mBounds.setEmpty();
519    mAdvances.clear();
520    mAdvances.resize(count, 0);
521    mAdvance = 0;
522    if (!(bidiFlags == kBidi_Force_LTR || bidiFlags == kBidi_Force_RTL)) {
523        UBiDi* bidi = ubidi_open();
524        if (bidi) {
525            UErrorCode status = U_ZERO_ERROR;
526            UBiDiLevel bidiReq = bidiFlags;
527            if (bidiFlags == kBidi_Default_LTR) {
528                bidiReq = UBIDI_DEFAULT_LTR;
529            } else if (bidiFlags == kBidi_Default_RTL) {
530                bidiReq = UBIDI_DEFAULT_RTL;
531            }
532            ubidi_setPara(bidi, buf, bufSize, bidiReq, NULL, &status);
533            if (U_SUCCESS(status)) {
534                int paraDir = ubidi_getParaLevel(bidi) & kDirection_Mask;
535                ssize_t rc = ubidi_countRuns(bidi, &status);
536                if (!U_SUCCESS(status) || rc < 0) {
537                    ALOGW("error counting bidi runs, status = %d", status);
538                }
539                if (!U_SUCCESS(status) || rc <= 1) {
540                    isRtl = (paraDir == kBidi_RTL);
541                } else {
542                    doSingleRun = false;
543                    // iterate through runs
544                    for (ssize_t i = 0; i < (ssize_t)rc; i++) {
545                        int32_t startRun = -1;
546                        int32_t lengthRun = -1;
547                        UBiDiDirection runDir = ubidi_getVisualRun(bidi, i, &startRun, &lengthRun);
548                        if (startRun == -1 || lengthRun == -1) {
549                            ALOGE("invalid visual run");
550                            // skip the invalid run
551                            continue;
552                        }
553                        int32_t endRun = std::min(startRun + lengthRun, int32_t(start + count));
554                        startRun = std::max(startRun, int32_t(start));
555                        lengthRun = endRun - startRun;
556                        if (lengthRun > 0) {
557                            isRtl = (runDir == UBIDI_RTL);
558                            doLayoutRunCached(buf, startRun, lengthRun, bufSize, isRtl, &ctx,
559                                start);
560                        }
561                    }
562                }
563            } else {
564                ALOGE("error calling ubidi_setPara, status = %d", status);
565            }
566            ubidi_close(bidi);
567        } else {
568            ALOGE("error creating bidi object");
569        }
570    }
571    if (doSingleRun) {
572        doLayoutRunCached(buf, start, count, bufSize, isRtl, &ctx, start);
573    }
574    ctx.clearHbFonts();
575}
576
577void Layout::doLayoutRunCached(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
578        bool isRtl, LayoutContext* ctx, size_t dstStart) {
579    if (!isRtl) {
580        // left to right
581        size_t wordstart = start == bufSize ? start : getPrevWordBreak(buf, start + 1);
582        size_t wordend;
583        for (size_t iter = start; iter < start + count; iter = wordend) {
584            wordend = getNextWordBreak(buf, iter, bufSize);
585            size_t wordcount = std::min(start + count, wordend) - iter;
586            doLayoutWord(buf + wordstart, iter - wordstart, wordcount, wordend - wordstart,
587                    isRtl, ctx, iter - dstStart);
588            wordstart = wordend;
589        }
590    } else {
591        // right to left
592        size_t wordstart;
593        size_t end = start + count;
594        size_t wordend = end == 0 ? 0 : getNextWordBreak(buf, end - 1, bufSize);
595        for (size_t iter = end; iter > start; iter = wordstart) {
596            wordstart = getPrevWordBreak(buf, iter);
597            size_t bufStart = std::max(start, wordstart);
598            doLayoutWord(buf + wordstart, bufStart - wordstart, iter - bufStart,
599                    wordend - wordstart, isRtl, ctx, bufStart - dstStart);
600            wordend = wordstart;
601        }
602    }
603}
604
605void Layout::doLayoutWord(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
606        bool isRtl, LayoutContext* ctx, size_t bufStart) {
607    LayoutCache& cache = LayoutEngine::getInstance().layoutCache;
608    LayoutCacheKey key(mCollection, ctx->paint, ctx->style, buf, start, count, bufSize, isRtl);
609    bool skipCache = ctx->paint.skipCache();
610    if (skipCache) {
611        Layout layout;
612        key.doLayout(&layout, ctx, mCollection);
613        appendLayout(&layout, bufStart);
614    } else {
615        Layout* layout = cache.get(key, ctx, mCollection);
616        appendLayout(layout, bufStart);
617    }
618}
619
620static void addFeatures(const string &str, vector<hb_feature_t>* features) {
621    if (!str.size())
622        return;
623
624    const char* start = str.c_str();
625    const char* end = start + str.size();
626
627    while (start < end) {
628        static hb_feature_t feature;
629        const char* p = strchr(start, ',');
630        if (!p)
631            p = end;
632        /* We do not allow setting features on ranges.  As such, reject any
633         * setting that has non-universal range. */
634        if (hb_feature_from_string (start, p - start, &feature)
635                && feature.start == 0 && feature.end == (unsigned int) -1)
636            features->push_back(feature);
637        start = p + 1;
638    }
639}
640
641void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
642        bool isRtl, LayoutContext* ctx) {
643    hb_buffer_t* buffer = LayoutEngine::getInstance().hbBuffer;
644    vector<FontCollection::Run> items;
645    mCollection->itemize(buf + start, count, ctx->style, &items);
646    if (isRtl) {
647        std::reverse(items.begin(), items.end());
648    }
649
650    vector<hb_feature_t> features;
651    // Disable default-on non-required ligature features if letter-spacing
652    // See http://dev.w3.org/csswg/css-text-3/#letter-spacing-property
653    // "When the effective spacing between two characters is not zero (due to
654    // either justification or a non-zero value of letter-spacing), user agents
655    // should not apply optional ligatures."
656    if (fabs(ctx->paint.letterSpacing) > 0.03)
657    {
658        static const hb_feature_t no_liga = { HB_TAG('l', 'i', 'g', 'a'), 0, 0, ~0u };
659        static const hb_feature_t no_clig = { HB_TAG('c', 'l', 'i', 'g'), 0, 0, ~0u };
660        features.push_back(no_liga);
661        features.push_back(no_clig);
662    }
663    addFeatures(ctx->paint.fontFeatureSettings, &features);
664
665    double size = ctx->paint.size;
666    double scaleX = ctx->paint.scaleX;
667    double letterSpace = ctx->paint.letterSpacing * size * scaleX;
668    double letterSpaceHalf = letterSpace * .5;
669
670    float x = mAdvance;
671    float y = 0;
672    for (size_t run_ix = 0; run_ix < items.size(); run_ix++) {
673        FontCollection::Run &run = items[run_ix];
674        if (run.fakedFont.font == NULL) {
675            ALOGE("no font for run starting u+%04x length %d", buf[run.start], run.end - run.start);
676            continue;
677        }
678        int font_ix = findFace(run.fakedFont, ctx);
679        ctx->paint.font = mFaces[font_ix].font;
680        ctx->paint.fakery = mFaces[font_ix].fakery;
681        hb_font_t* hbFont = ctx->hbFonts[font_ix];
682#ifdef VERBOSE
683        std::cout << "Run " << run_ix << ", font " << font_ix <<
684            " [" << run.start << ":" << run.end << "]" << std::endl;
685#endif
686
687        hb_font_set_ppem(hbFont, size * scaleX, size);
688        hb_font_set_scale(hbFont, HBFloatToFixed(size * scaleX), HBFloatToFixed(size));
689
690        // TODO: if there are multiple scripts within a font in an RTL run,
691        // we need to reorder those runs. This is unlikely with our current
692        // font stack, but should be done for correctness.
693        ssize_t srunend;
694        for (ssize_t srunstart = run.start; srunstart < run.end; srunstart = srunend) {
695            srunend = srunstart;
696            hb_script_t script = getScriptRun(buf + start, run.end, &srunend);
697
698            hb_buffer_reset(buffer);
699            hb_buffer_set_script(buffer, script);
700            hb_buffer_set_direction(buffer, isRtl? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
701            FontLanguage language = ctx->style.getLanguage();
702            if (language) {
703                string lang = language.getString();
704                hb_buffer_set_language(buffer, hb_language_from_string(lang.c_str(), -1));
705            }
706            hb_buffer_add_utf16(buffer, buf, bufSize, srunstart + start, srunend - srunstart);
707            hb_shape(hbFont, buffer, features.empty() ? NULL : &features[0], features.size());
708            unsigned int numGlyphs;
709            hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, &numGlyphs);
710            hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buffer, NULL);
711            if (numGlyphs)
712            {
713                mAdvances[info[0].cluster - start] += letterSpaceHalf;
714                x += letterSpaceHalf;
715            }
716            for (unsigned int i = 0; i < numGlyphs; i++) {
717    #ifdef VERBOSE
718                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 <<
719                ": " << HBFixedToFloat(positions[i].x_advance) << "; " << positions[i].x_offset << ", " << positions[i].y_offset << std::endl;
720    #endif
721                if (i > 0 && info[i - 1].cluster != info[i].cluster) {
722                    mAdvances[info[i - 1].cluster - start] += letterSpaceHalf;
723                    mAdvances[info[i].cluster - start] += letterSpaceHalf;
724                    x += letterSpaceHalf;
725                }
726
727                hb_codepoint_t glyph_ix = info[i].codepoint;
728                float xoff = HBFixedToFloat(positions[i].x_offset);
729                float yoff = -HBFixedToFloat(positions[i].y_offset);
730                xoff += yoff * ctx->paint.skewX;
731                LayoutGlyph glyph = {font_ix, glyph_ix, x + xoff, y + yoff};
732                mGlyphs.push_back(glyph);
733                float xAdvance = HBFixedToFloat(positions[i].x_advance);
734                MinikinRect glyphBounds;
735                ctx->paint.font->GetBounds(&glyphBounds, glyph_ix, ctx->paint);
736                glyphBounds.offset(x + xoff, y + yoff);
737                mBounds.join(glyphBounds);
738                mAdvances[info[i].cluster - start] += xAdvance;
739                x += xAdvance;
740            }
741            if (numGlyphs)
742            {
743                mAdvances[info[numGlyphs - 1].cluster - start] += letterSpaceHalf;
744                x += letterSpaceHalf;
745            }
746        }
747    }
748    mAdvance = x;
749}
750
751void Layout::appendLayout(Layout* src, size_t start) {
752    // Note: size==1 is by far most common, should have specialized vector for this
753    std::vector<int> fontMap;
754    for (size_t i = 0; i < src->mFaces.size(); i++) {
755        int font_ix = findFace(src->mFaces[i], NULL);
756        fontMap.push_back(font_ix);
757    }
758    int x0 = mAdvance;
759    for (size_t i = 0; i < src->mGlyphs.size(); i++) {
760        LayoutGlyph& srcGlyph = src->mGlyphs[i];
761        int font_ix = fontMap[srcGlyph.font_ix];
762        unsigned int glyph_id = srcGlyph.glyph_id;
763        float x = x0 + srcGlyph.x;
764        float y = srcGlyph.y;
765        LayoutGlyph glyph = {font_ix, glyph_id, x, y};
766        mGlyphs.push_back(glyph);
767    }
768    for (size_t i = 0; i < src->mAdvances.size(); i++) {
769        mAdvances[i + start] = src->mAdvances[i];
770    }
771    MinikinRect srcBounds(src->mBounds);
772    srcBounds.offset(x0, 0);
773    mBounds.join(srcBounds);
774    mAdvance += src->mAdvance;
775}
776
777void Layout::draw(Bitmap* surface, int x0, int y0, float size) const {
778    /*
779    TODO: redo as MinikinPaint settings
780    if (mProps.hasTag(minikinHinting)) {
781        int hintflags = mProps.value(minikinHinting).getIntValue();
782        if (hintflags & 1) load_flags |= FT_LOAD_NO_HINTING;
783        if (hintflags & 2) load_flags |= FT_LOAD_NO_AUTOHINT;
784    }
785    */
786    for (size_t i = 0; i < mGlyphs.size(); i++) {
787        const LayoutGlyph& glyph = mGlyphs[i];
788        MinikinFont* mf = mFaces[glyph.font_ix].font;
789        MinikinFontFreeType* face = static_cast<MinikinFontFreeType*>(mf);
790        GlyphBitmap glyphBitmap;
791        MinikinPaint paint;
792        paint.size = size;
793        bool ok = face->Render(glyph.glyph_id, paint, &glyphBitmap);
794        printf("glyphBitmap.width=%d, glyphBitmap.height=%d (%d, %d) x=%f, y=%f, ok=%d\n",
795            glyphBitmap.width, glyphBitmap.height, glyphBitmap.left, glyphBitmap.top, glyph.x, glyph.y, ok);
796        if (ok) {
797            surface->drawGlyph(glyphBitmap,
798                x0 + int(floor(glyph.x + 0.5)), y0 + int(floor(glyph.y + 0.5)));
799        }
800    }
801}
802
803size_t Layout::nGlyphs() const {
804    return mGlyphs.size();
805}
806
807MinikinFont* Layout::getFont(int i) const {
808    const LayoutGlyph& glyph = mGlyphs[i];
809    return mFaces[glyph.font_ix].font;
810}
811
812FontFakery Layout::getFakery(int i) const {
813    const LayoutGlyph& glyph = mGlyphs[i];
814    return mFaces[glyph.font_ix].fakery;
815}
816
817unsigned int Layout::getGlyphId(int i) const {
818    const LayoutGlyph& glyph = mGlyphs[i];
819    return glyph.glyph_id;
820}
821
822float Layout::getX(int i) const {
823    const LayoutGlyph& glyph = mGlyphs[i];
824    return glyph.x;
825}
826
827float Layout::getY(int i) const {
828    const LayoutGlyph& glyph = mGlyphs[i];
829    return glyph.y;
830}
831
832float Layout::getAdvance() const {
833    return mAdvance;
834}
835
836void Layout::getAdvances(float* advances) {
837    memcpy(advances, &mAdvances[0], mAdvances.size() * sizeof(float));
838}
839
840void Layout::getBounds(MinikinRect* bounds) {
841    bounds->set(mBounds);
842}
843
844void Layout::purgeCaches() {
845    AutoMutex _l(gMinikinLock);
846    LayoutCache& layoutCache = LayoutEngine::getInstance().layoutCache;
847    layoutCache.clear();
848    HbFaceCache& hbCache = LayoutEngine::getInstance().hbFaceCache;
849    hbCache.mCache.clear();
850}
851
852}  // namespace android
853