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