Layout.cpp revision 0297ee985c26b49fc2a3b0941db354c27f436bbf
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 return FontStyle(weight, italic); 348} 349 350static hb_script_t codePointToScript(hb_codepoint_t codepoint) { 351 static hb_unicode_funcs_t* u = 0; 352 if (!u) { 353 u = hb_icu_get_unicode_funcs(); 354 } 355 return hb_unicode_script(u, codepoint); 356} 357 358static hb_codepoint_t decodeUtf16(const uint16_t* chars, size_t len, ssize_t* iter) { 359 const uint16_t v = chars[(*iter)++]; 360 // test whether v in (0xd800..0xdfff), lead or trail surrogate 361 if ((v & 0xf800) == 0xd800) { 362 // test whether v in (0xd800..0xdbff), lead surrogate 363 if (size_t(*iter) < len && (v & 0xfc00) == 0xd800) { 364 const uint16_t v2 = chars[(*iter)++]; 365 // test whether v2 in (0xdc00..0xdfff), trail surrogate 366 if ((v2 & 0xfc00) == 0xdc00) { 367 // (0xd800 0xdc00) in utf-16 maps to 0x10000 in ucs-32 368 const hb_codepoint_t delta = (0xd800 << 10) + 0xdc00 - 0x10000; 369 return (((hb_codepoint_t)v) << 10) + v2 - delta; 370 } 371 (*iter) -= 2; 372 return ~0u; 373 } else { 374 (*iter)--; 375 return ~0u; 376 } 377 } else { 378 return v; 379 } 380} 381 382static hb_script_t getScriptRun(const uint16_t* chars, size_t len, ssize_t* iter) { 383 if (size_t(*iter) == len) { 384 return HB_SCRIPT_UNKNOWN; 385 } 386 uint32_t cp = decodeUtf16(chars, len, iter); 387 hb_script_t current_script = codePointToScript(cp); 388 for (;;) { 389 if (size_t(*iter) == len) 390 break; 391 const ssize_t prev_iter = *iter; 392 cp = decodeUtf16(chars, len, iter); 393 const hb_script_t script = codePointToScript(cp); 394 if (script != current_script) { 395 if (current_script == HB_SCRIPT_INHERITED || 396 current_script == HB_SCRIPT_COMMON) { 397 current_script = script; 398 } else if (script == HB_SCRIPT_INHERITED || 399 script == HB_SCRIPT_COMMON) { 400 continue; 401 } else { 402 *iter = prev_iter; 403 break; 404 } 405 } 406 } 407 if (current_script == HB_SCRIPT_INHERITED) { 408 current_script = HB_SCRIPT_COMMON; 409 } 410 411 return current_script; 412} 413 414/** 415 * For the purpose of layout, a word break is a boundary with no 416 * kerning or complex script processing. This is necessarily a 417 * heuristic, but should be accurate most of the time. 418 */ 419static bool isWordBreak(int c) { 420 if (c == ' ' || (c >= 0x2000 && c <= 0x200a) || c == 0x3000) { 421 // spaces 422 return true; 423 } 424 if ((c >= 0x3400 && c <= 0x9fff)) { 425 // CJK ideographs (and yijing hexagram symbols) 426 return true; 427 } 428 // Note: kana is not included, as sophisticated fonts may kern kana 429 return false; 430} 431 432/** 433 * Return offset of previous word break. It is either < offset or == 0. 434 */ 435static size_t getPrevWordBreak(const uint16_t* chars, size_t offset) { 436 if (offset == 0) return 0; 437 if (isWordBreak(chars[offset - 1])) { 438 return offset - 1; 439 } 440 for (size_t i = offset - 1; i > 0; i--) { 441 if (isWordBreak(chars[i - 1])) { 442 return i; 443 } 444 } 445 return 0; 446} 447 448/** 449 * Return offset of next word break. It is either > offset or == len. 450 */ 451static size_t getNextWordBreak(const uint16_t* chars, size_t offset, size_t len) { 452 if (offset >= len) return len; 453 if (isWordBreak(chars[offset])) { 454 return offset + 1; 455 } 456 for (size_t i = offset + 1; i < len; i++) { 457 if (isWordBreak(chars[i])) { 458 return i; 459 } 460 } 461 return len; 462} 463 464// deprecated API, to avoid breaking client 465void Layout::doLayout(const uint16_t* buf, size_t nchars) { 466 doLayout(buf, 0, nchars, nchars, mCssString); 467} 468 469// TODO: use some standard implementation 470template<typename T> 471static T mymin(const T& a, const T& b) { 472 return a < b ? a : b; 473} 474 475template<typename T> 476static T mymax(const T& a, const T& b) { 477 return a > b ? a : b; 478} 479 480static void clearHbFonts(LayoutContext* ctx) { 481 for (size_t i = 0; i < ctx->hbFonts.size(); i++) { 482 hb_font_destroy(ctx->hbFonts[i]); 483 } 484 ctx->hbFonts.clear(); 485} 486 487// TODO: API should probably take context 488void Layout::doLayout(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 489 const std::string& css) { 490 AutoMutex _l(gMinikinLock); 491 LayoutContext ctx; 492 493 ctx.props.parse(css); 494 ctx.style = styleFromCss(ctx.props); 495 496 double size = ctx.props.value(fontSize).getFloatValue(); 497 ctx.paint.size = size; 498 int bidiFlags = ctx.props.hasTag(minikinBidi) ? ctx.props.value(minikinBidi).getIntValue() : 0; 499 bool isRtl = (bidiFlags & kDirection_Mask) != 0; 500 bool doSingleRun = true; 501 502 mGlyphs.clear(); 503 mFaces.clear(); 504 mBounds.setEmpty(); 505 mAdvances.clear(); 506 mAdvances.resize(count, 0); 507 mAdvance = 0; 508 if (!(bidiFlags == kBidi_Force_LTR || bidiFlags == kBidi_Force_RTL)) { 509 UBiDi* bidi = ubidi_open(); 510 if (bidi) { 511 UErrorCode status = U_ZERO_ERROR; 512 UBiDiLevel bidiReq = bidiFlags; 513 if (bidiFlags == kBidi_Default_LTR) { 514 bidiReq = UBIDI_DEFAULT_LTR; 515 } else if (bidiFlags == kBidi_Default_RTL) { 516 bidiReq = UBIDI_DEFAULT_RTL; 517 } 518 ubidi_setPara(bidi, buf, bufSize, bidiReq, NULL, &status); 519 if (U_SUCCESS(status)) { 520 int paraDir = ubidi_getParaLevel(bidi) & kDirection_Mask; 521 ssize_t rc = ubidi_countRuns(bidi, &status); 522 if (!U_SUCCESS(status) || rc < 0) { 523 ALOGW("error counting bidi runs, status = %d", status); 524 } 525 if (!U_SUCCESS(status) || rc <= 1) { 526 isRtl = (paraDir == kBidi_RTL); 527 } else { 528 doSingleRun = false; 529 // iterate through runs 530 for (ssize_t i = 0; i < (ssize_t)rc; i++) { 531 int32_t startRun = -1; 532 int32_t lengthRun = -1; 533 UBiDiDirection runDir = ubidi_getVisualRun(bidi, i, &startRun, &lengthRun); 534 if (startRun == -1 || lengthRun == -1) { 535 ALOGE("invalid visual run"); 536 // skip the invalid run 537 continue; 538 } 539 isRtl = (runDir == UBIDI_RTL); 540 // TODO: min/max with context 541 doLayoutRunCached(buf, startRun, lengthRun, bufSize, isRtl, &ctx); 542 } 543 } 544 } else { 545 ALOGE("error calling ubidi_setPara, status = %d", status); 546 } 547 ubidi_close(bidi); 548 } else { 549 ALOGE("error creating bidi object"); 550 } 551 } 552 if (doSingleRun) { 553 doLayoutRunCached(buf, start, count, bufSize, isRtl, &ctx); 554 } 555 clearHbFonts(&ctx); 556} 557 558void Layout::doLayoutRunCached(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 559 bool isRtl, LayoutContext* ctx) { 560 if (!isRtl) { 561 // left to right 562 size_t wordstart = start == bufSize ? start : getPrevWordBreak(buf, start + 1); 563 size_t wordend; 564 for (size_t iter = start; iter < start + count; iter = wordend) { 565 wordend = getNextWordBreak(buf, iter, bufSize); 566 size_t wordcount = mymin(start + count, wordend) - iter; 567 doLayoutWord(buf + wordstart, iter - wordstart, wordcount, wordend - wordstart, 568 isRtl, ctx, iter); 569 wordstart = wordend; 570 } 571 } else { 572 // right to left 573 size_t wordstart; 574 size_t end = start + count; 575 size_t wordend = end == 0 ? 0 : getNextWordBreak(buf, end - 1, bufSize); 576 for (size_t iter = end; iter > start; iter = wordstart) { 577 wordstart = getPrevWordBreak(buf, iter); 578 size_t bufStart = mymax(start, wordstart); 579 doLayoutWord(buf + wordstart, bufStart - wordstart, iter - bufStart, 580 wordend - wordstart, isRtl, ctx, bufStart); 581 wordend = wordstart; 582 } 583 } 584} 585 586void Layout::doLayoutWord(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 587 bool isRtl, LayoutContext* ctx, size_t bufStart) { 588 LayoutCache& cache = LayoutEngine::getInstance().layoutCache; 589 LayoutCacheKey key(mCollection, ctx->paint, ctx->style, buf, start, count, bufSize, isRtl); 590 Layout* value = cache.mCache.get(key); 591 if (value == NULL) { 592 value = new Layout(); 593 value->setFontCollection(mCollection); 594 value->mAdvances.resize(count, 0); 595 clearHbFonts(ctx); 596 // Note: we do the layout from the copy stored in the key, in case a 597 // badly-behaved client is mutating the buffer in a separate thread. 598 value->doLayoutRun(key.textBuf(), start, count, bufSize, isRtl, ctx); 599 } 600 appendLayout(value, bufStart); 601 cache.mCache.put(key, value); 602 603} 604 605void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 606 bool isRtl, LayoutContext* ctx) { 607 hb_buffer_t* buffer = LayoutEngine::getInstance().hbBuffer; 608 vector<FontCollection::Run> items; 609 mCollection->itemize(buf + start, count, ctx->style, &items); 610 if (isRtl) { 611 std::reverse(items.begin(), items.end()); 612 } 613 614 float x = mAdvance; 615 float y = 0; 616 for (size_t run_ix = 0; run_ix < items.size(); run_ix++) { 617 FontCollection::Run &run = items[run_ix]; 618 if (run.font == NULL) { 619 ALOGE("no font for run starting u+%04x length %d", buf[run.start], run.end - run.start); 620 continue; 621 } 622 int font_ix = findFace(run.font, ctx); 623 ctx->paint.font = mFaces[font_ix]; 624 hb_font_t* hbFont = ctx->hbFonts[font_ix]; 625#ifdef VERBOSE 626 std::cout << "Run " << run_ix << ", font " << font_ix << 627 " [" << run.start << ":" << run.end << "]" << std::endl; 628#endif 629 double size = ctx->paint.size; 630 hb_font_set_ppem(hbFont, size, size); 631 hb_font_set_scale(hbFont, HBFloatToFixed(size), HBFloatToFixed(size)); 632 633 // TODO: if there are multiple scripts within a font in an RTL run, 634 // we need to reorder those runs. This is unlikely with our current 635 // font stack, but should be done for correctness. 636 ssize_t srunend; 637 for (ssize_t srunstart = run.start; srunstart < run.end; srunstart = srunend) { 638 srunend = srunstart; 639 hb_script_t script = getScriptRun(buf + start, run.end, &srunend); 640 641 hb_buffer_reset(buffer); 642 hb_buffer_set_script(buffer, script); 643 hb_buffer_set_direction(buffer, isRtl? HB_DIRECTION_RTL : HB_DIRECTION_LTR); 644 hb_buffer_add_utf16(buffer, buf, bufSize, srunstart + start, srunend - srunstart); 645 hb_shape(hbFont, buffer, NULL, 0); 646 unsigned int numGlyphs; 647 hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, &numGlyphs); 648 hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buffer, NULL); 649 for (unsigned int i = 0; i < numGlyphs; i++) { 650 #ifdef VERBOSE 651 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 << 652 ": " << HBFixedToFloat(positions[i].x_advance) << "; " << positions[i].x_offset << ", " << positions[i].y_offset << std::endl; 653 #endif 654 hb_codepoint_t glyph_ix = info[i].codepoint; 655 float xoff = HBFixedToFloat(positions[i].x_offset); 656 float yoff = HBFixedToFloat(positions[i].y_offset); 657 LayoutGlyph glyph = {font_ix, glyph_ix, x + xoff, y + yoff}; 658 mGlyphs.push_back(glyph); 659 float xAdvance = HBFixedToFloat(positions[i].x_advance); 660 MinikinRect glyphBounds; 661 ctx->paint.font->GetBounds(&glyphBounds, glyph_ix, ctx->paint); 662 glyphBounds.offset(x + xoff, y + yoff); 663 mBounds.join(glyphBounds); 664 size_t cluster = info[i].cluster - start; 665 mAdvances[cluster] += xAdvance; 666 x += xAdvance; 667 } 668 } 669 } 670 mAdvance = x; 671} 672 673void Layout::appendLayout(Layout* src, size_t start) { 674 // Note: size==1 is by far most common, should have specialized vector for this 675 std::vector<int> fontMap; 676 for (size_t i = 0; i < src->mFaces.size(); i++) { 677 int font_ix = findFace(src->mFaces[i], NULL); 678 fontMap.push_back(font_ix); 679 } 680 int x0 = mAdvance; 681 for (size_t i = 0; i < src->mGlyphs.size(); i++) { 682 LayoutGlyph& srcGlyph = src->mGlyphs[i]; 683 int font_ix = fontMap[srcGlyph.font_ix]; 684 unsigned int glyph_id = srcGlyph.glyph_id; 685 float x = x0 + srcGlyph.x; 686 float y = srcGlyph.y; 687 LayoutGlyph glyph = {font_ix, glyph_id, x, y}; 688 mGlyphs.push_back(glyph); 689 } 690 for (size_t i = 0; i < src->mAdvances.size(); i++) { 691 mAdvances[i + start] = src->mAdvances[i]; 692 } 693 MinikinRect srcBounds(src->mBounds); 694 srcBounds.offset(x0, 0); 695 mBounds.join(srcBounds); 696 mAdvance += src->mAdvance; 697} 698 699void Layout::draw(Bitmap* surface, int x0, int y0, float size) const { 700 /* 701 TODO: redo as MinikinPaint settings 702 if (mProps.hasTag(minikinHinting)) { 703 int hintflags = mProps.value(minikinHinting).getIntValue(); 704 if (hintflags & 1) load_flags |= FT_LOAD_NO_HINTING; 705 if (hintflags & 2) load_flags |= FT_LOAD_NO_AUTOHINT; 706 } 707 */ 708 for (size_t i = 0; i < mGlyphs.size(); i++) { 709 const LayoutGlyph& glyph = mGlyphs[i]; 710 MinikinFont* mf = mFaces[glyph.font_ix]; 711 MinikinFontFreeType* face = static_cast<MinikinFontFreeType*>(mf); 712 GlyphBitmap glyphBitmap; 713 MinikinPaint paint; 714 paint.size = size; 715 bool ok = face->Render(glyph.glyph_id, paint, &glyphBitmap); 716 printf("glyphBitmap.width=%d, glyphBitmap.height=%d (%d, %d) x=%f, y=%f, ok=%d\n", 717 glyphBitmap.width, glyphBitmap.height, glyphBitmap.left, glyphBitmap.top, glyph.x, glyph.y, ok); 718 if (ok) { 719 surface->drawGlyph(glyphBitmap, 720 x0 + int(floor(glyph.x + 0.5)), y0 + int(floor(glyph.y + 0.5))); 721 } 722 } 723} 724 725void Layout::setProperties(const string& css) { 726 mCssString = css; 727} 728 729size_t Layout::nGlyphs() const { 730 return mGlyphs.size(); 731} 732 733MinikinFont* Layout::getFont(int i) const { 734 const LayoutGlyph& glyph = mGlyphs[i]; 735 return mFaces[glyph.font_ix]; 736} 737 738unsigned int Layout::getGlyphId(int i) const { 739 const LayoutGlyph& glyph = mGlyphs[i]; 740 return glyph.glyph_id; 741} 742 743float Layout::getX(int i) const { 744 const LayoutGlyph& glyph = mGlyphs[i]; 745 return glyph.x; 746} 747 748float Layout::getY(int i) const { 749 const LayoutGlyph& glyph = mGlyphs[i]; 750 return glyph.y; 751} 752 753float Layout::getAdvance() const { 754 return mAdvance; 755} 756 757void Layout::getAdvances(float* advances) { 758 memcpy(advances, &mAdvances[0], mAdvances.size() * sizeof(float)); 759} 760 761void Layout::getBounds(MinikinRect* bounds) { 762 bounds->set(mBounds); 763} 764 765} // namespace android 766