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