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