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