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