1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ui/gfx/render_text_harfbuzz.h"
6
7 #include <limits>
8 #include <map>
9
10 #include "base/i18n/bidi_line_iterator.h"
11 #include "base/i18n/break_iterator.h"
12 #include "base/i18n/char_iterator.h"
13 #include "base/lazy_instance.h"
14 #include "third_party/harfbuzz-ng/src/hb.h"
15 #include "third_party/icu/source/common/unicode/ubidi.h"
16 #include "third_party/skia/include/core/SkColor.h"
17 #include "third_party/skia/include/core/SkTypeface.h"
18 #include "ui/gfx/canvas.h"
19 #include "ui/gfx/font_fallback.h"
20 #include "ui/gfx/font_render_params.h"
21 #include "ui/gfx/utf16_indexing.h"
22
23 #if defined(OS_WIN)
24 #include "ui/gfx/font_fallback_win.h"
25 #endif
26
27 namespace gfx {
28
29 namespace {
30
31 // Text length limit. Longer strings are slow and not fully tested.
32 const size_t kMaxTextLength = 10000;
33
34 // The maximum number of scripts a Unicode character can belong to. This value
35 // is arbitrarily chosen to be a good limit because it is unlikely for a single
36 // character to belong to more scripts.
37 const size_t kMaxScripts = 5;
38
39 // Maps from code points to glyph indices in a font.
40 typedef std::map<uint32_t, uint16_t> GlyphCache;
41
42 // Font data provider for HarfBuzz using Skia. Copied from Blink.
43 // TODO(ckocagil): Eliminate the duplication. http://crbug.com/368375
44 struct FontData {
FontDatagfx::__anonaeb591460111::FontData45 FontData(GlyphCache* glyph_cache) : glyph_cache_(glyph_cache) {}
46
47 SkPaint paint_;
48 GlyphCache* glyph_cache_;
49 };
50
SkiaScalarToHarfBuzzPosition(SkScalar value)51 hb_position_t SkiaScalarToHarfBuzzPosition(SkScalar value) {
52 return SkScalarToFixed(value);
53 }
54
55 // Deletes the object at the given pointer after casting it to the given type.
56 template<typename Type>
DeleteByType(void * data)57 void DeleteByType(void* data) {
58 Type* typed_data = reinterpret_cast<Type*>(data);
59 delete typed_data;
60 }
61
62 template<typename Type>
DeleteArrayByType(void * data)63 void DeleteArrayByType(void* data) {
64 Type* typed_data = reinterpret_cast<Type*>(data);
65 delete[] typed_data;
66 }
67
68 // Outputs the |width| and |extents| of the glyph with index |codepoint| in
69 // |paint|'s font.
GetGlyphWidthAndExtents(SkPaint * paint,hb_codepoint_t codepoint,hb_position_t * width,hb_glyph_extents_t * extents)70 void GetGlyphWidthAndExtents(SkPaint* paint,
71 hb_codepoint_t codepoint,
72 hb_position_t* width,
73 hb_glyph_extents_t* extents) {
74 DCHECK_LE(codepoint, 0xFFFFU);
75 paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding);
76
77 SkScalar sk_width;
78 SkRect sk_bounds;
79 uint16_t glyph = codepoint;
80
81 paint->getTextWidths(&glyph, sizeof(glyph), &sk_width, &sk_bounds);
82 if (width)
83 *width = SkiaScalarToHarfBuzzPosition(sk_width);
84 if (extents) {
85 // Invert y-axis because Skia is y-grows-down but we set up HarfBuzz to be
86 // y-grows-up.
87 extents->x_bearing = SkiaScalarToHarfBuzzPosition(sk_bounds.fLeft);
88 extents->y_bearing = SkiaScalarToHarfBuzzPosition(-sk_bounds.fTop);
89 extents->width = SkiaScalarToHarfBuzzPosition(sk_bounds.width());
90 extents->height = SkiaScalarToHarfBuzzPosition(-sk_bounds.height());
91 }
92 }
93
94 // Writes the |glyph| index for the given |unicode| code point. Returns whether
95 // the glyph exists, i.e. it is not a missing glyph.
GetGlyph(hb_font_t * font,void * data,hb_codepoint_t unicode,hb_codepoint_t variation_selector,hb_codepoint_t * glyph,void * user_data)96 hb_bool_t GetGlyph(hb_font_t* font,
97 void* data,
98 hb_codepoint_t unicode,
99 hb_codepoint_t variation_selector,
100 hb_codepoint_t* glyph,
101 void* user_data) {
102 FontData* font_data = reinterpret_cast<FontData*>(data);
103 GlyphCache* cache = font_data->glyph_cache_;
104
105 bool exists = cache->count(unicode) != 0;
106 if (!exists) {
107 SkPaint* paint = &font_data->paint_;
108 paint->setTextEncoding(SkPaint::kUTF32_TextEncoding);
109 paint->textToGlyphs(&unicode, sizeof(hb_codepoint_t), &(*cache)[unicode]);
110 }
111 *glyph = (*cache)[unicode];
112 return !!*glyph;
113 }
114
115 // Returns the horizontal advance value of the |glyph|.
GetGlyphHorizontalAdvance(hb_font_t * font,void * data,hb_codepoint_t glyph,void * user_data)116 hb_position_t GetGlyphHorizontalAdvance(hb_font_t* font,
117 void* data,
118 hb_codepoint_t glyph,
119 void* user_data) {
120 FontData* font_data = reinterpret_cast<FontData*>(data);
121 hb_position_t advance = 0;
122
123 GetGlyphWidthAndExtents(&font_data->paint_, glyph, &advance, 0);
124 return advance;
125 }
126
GetGlyphHorizontalOrigin(hb_font_t * font,void * data,hb_codepoint_t glyph,hb_position_t * x,hb_position_t * y,void * user_data)127 hb_bool_t GetGlyphHorizontalOrigin(hb_font_t* font,
128 void* data,
129 hb_codepoint_t glyph,
130 hb_position_t* x,
131 hb_position_t* y,
132 void* user_data) {
133 // Just return true, like the HarfBuzz-FreeType implementation.
134 return true;
135 }
136
GetGlyphKerning(FontData * font_data,hb_codepoint_t first_glyph,hb_codepoint_t second_glyph)137 hb_position_t GetGlyphKerning(FontData* font_data,
138 hb_codepoint_t first_glyph,
139 hb_codepoint_t second_glyph) {
140 SkTypeface* typeface = font_data->paint_.getTypeface();
141 const uint16_t glyphs[2] = { static_cast<uint16_t>(first_glyph),
142 static_cast<uint16_t>(second_glyph) };
143 int32_t kerning_adjustments[1] = { 0 };
144
145 if (!typeface->getKerningPairAdjustments(glyphs, 2, kerning_adjustments))
146 return 0;
147
148 SkScalar upm = SkIntToScalar(typeface->getUnitsPerEm());
149 SkScalar size = font_data->paint_.getTextSize();
150 return SkiaScalarToHarfBuzzPosition(
151 SkScalarMulDiv(SkIntToScalar(kerning_adjustments[0]), size, upm));
152 }
153
GetGlyphHorizontalKerning(hb_font_t * font,void * data,hb_codepoint_t left_glyph,hb_codepoint_t right_glyph,void * user_data)154 hb_position_t GetGlyphHorizontalKerning(hb_font_t* font,
155 void* data,
156 hb_codepoint_t left_glyph,
157 hb_codepoint_t right_glyph,
158 void* user_data) {
159 FontData* font_data = reinterpret_cast<FontData*>(data);
160 if (font_data->paint_.isVerticalText()) {
161 // We don't support cross-stream kerning.
162 return 0;
163 }
164
165 return GetGlyphKerning(font_data, left_glyph, right_glyph);
166 }
167
GetGlyphVerticalKerning(hb_font_t * font,void * data,hb_codepoint_t top_glyph,hb_codepoint_t bottom_glyph,void * user_data)168 hb_position_t GetGlyphVerticalKerning(hb_font_t* font,
169 void* data,
170 hb_codepoint_t top_glyph,
171 hb_codepoint_t bottom_glyph,
172 void* user_data) {
173 FontData* font_data = reinterpret_cast<FontData*>(data);
174 if (!font_data->paint_.isVerticalText()) {
175 // We don't support cross-stream kerning.
176 return 0;
177 }
178
179 return GetGlyphKerning(font_data, top_glyph, bottom_glyph);
180 }
181
182 // Writes the |extents| of |glyph|.
GetGlyphExtents(hb_font_t * font,void * data,hb_codepoint_t glyph,hb_glyph_extents_t * extents,void * user_data)183 hb_bool_t GetGlyphExtents(hb_font_t* font,
184 void* data,
185 hb_codepoint_t glyph,
186 hb_glyph_extents_t* extents,
187 void* user_data) {
188 FontData* font_data = reinterpret_cast<FontData*>(data);
189
190 GetGlyphWidthAndExtents(&font_data->paint_, glyph, 0, extents);
191 return true;
192 }
193
194 class FontFuncs {
195 public:
FontFuncs()196 FontFuncs() : font_funcs_(hb_font_funcs_create()) {
197 hb_font_funcs_set_glyph_func(font_funcs_, GetGlyph, 0, 0);
198 hb_font_funcs_set_glyph_h_advance_func(
199 font_funcs_, GetGlyphHorizontalAdvance, 0, 0);
200 hb_font_funcs_set_glyph_h_kerning_func(
201 font_funcs_, GetGlyphHorizontalKerning, 0, 0);
202 hb_font_funcs_set_glyph_h_origin_func(
203 font_funcs_, GetGlyphHorizontalOrigin, 0, 0);
204 hb_font_funcs_set_glyph_v_kerning_func(
205 font_funcs_, GetGlyphVerticalKerning, 0, 0);
206 hb_font_funcs_set_glyph_extents_func(
207 font_funcs_, GetGlyphExtents, 0, 0);
208 hb_font_funcs_make_immutable(font_funcs_);
209 }
210
~FontFuncs()211 ~FontFuncs() {
212 hb_font_funcs_destroy(font_funcs_);
213 }
214
get()215 hb_font_funcs_t* get() { return font_funcs_; }
216
217 private:
218 hb_font_funcs_t* font_funcs_;
219
220 DISALLOW_COPY_AND_ASSIGN(FontFuncs);
221 };
222
223 base::LazyInstance<FontFuncs>::Leaky g_font_funcs = LAZY_INSTANCE_INITIALIZER;
224
225 // Returns the raw data of the font table |tag|.
GetFontTable(hb_face_t * face,hb_tag_t tag,void * user_data)226 hb_blob_t* GetFontTable(hb_face_t* face, hb_tag_t tag, void* user_data) {
227 SkTypeface* typeface = reinterpret_cast<SkTypeface*>(user_data);
228
229 const size_t table_size = typeface->getTableSize(tag);
230 if (!table_size)
231 return 0;
232
233 scoped_ptr<char[]> buffer(new char[table_size]);
234 if (!buffer)
235 return 0;
236 size_t actual_size = typeface->getTableData(tag, 0, table_size, buffer.get());
237 if (table_size != actual_size)
238 return 0;
239
240 char* buffer_raw = buffer.release();
241 return hb_blob_create(buffer_raw, table_size, HB_MEMORY_MODE_WRITABLE,
242 buffer_raw, DeleteArrayByType<char>);
243 }
244
UnrefSkTypeface(void * data)245 void UnrefSkTypeface(void* data) {
246 SkTypeface* skia_face = reinterpret_cast<SkTypeface*>(data);
247 SkSafeUnref(skia_face);
248 }
249
250 // Wrapper class for a HarfBuzz face created from a given Skia face.
251 class HarfBuzzFace {
252 public:
HarfBuzzFace()253 HarfBuzzFace() : face_(NULL) {}
254
~HarfBuzzFace()255 ~HarfBuzzFace() {
256 if (face_)
257 hb_face_destroy(face_);
258 }
259
Init(SkTypeface * skia_face)260 void Init(SkTypeface* skia_face) {
261 SkSafeRef(skia_face);
262 face_ = hb_face_create_for_tables(GetFontTable, skia_face, UnrefSkTypeface);
263 DCHECK(face_);
264 }
265
get()266 hb_face_t* get() {
267 return face_;
268 }
269
270 private:
271 hb_face_t* face_;
272 };
273
274 // Creates a HarfBuzz font from the given Skia face and text size.
CreateHarfBuzzFont(SkTypeface * skia_face,int text_size,const FontRenderParams & params,bool background_is_transparent)275 hb_font_t* CreateHarfBuzzFont(SkTypeface* skia_face,
276 int text_size,
277 const FontRenderParams& params,
278 bool background_is_transparent) {
279 typedef std::pair<HarfBuzzFace, GlyphCache> FaceCache;
280
281 // TODO(ckocagil): This shouldn't grow indefinitely. Maybe use base::MRUCache?
282 static std::map<SkFontID, FaceCache> face_caches;
283
284 FaceCache* face_cache = &face_caches[skia_face->uniqueID()];
285 if (face_cache->first.get() == NULL)
286 face_cache->first.Init(skia_face);
287
288 hb_font_t* harfbuzz_font = hb_font_create(face_cache->first.get());
289 const int scale = SkScalarToFixed(text_size);
290 hb_font_set_scale(harfbuzz_font, scale, scale);
291 FontData* hb_font_data = new FontData(&face_cache->second);
292 hb_font_data->paint_.setTypeface(skia_face);
293 hb_font_data->paint_.setTextSize(text_size);
294 // TODO(ckocagil): Do we need to update these params later?
295 internal::ApplyRenderParams(params, background_is_transparent,
296 &hb_font_data->paint_);
297 hb_font_set_funcs(harfbuzz_font, g_font_funcs.Get().get(), hb_font_data,
298 DeleteByType<FontData>);
299 hb_font_make_immutable(harfbuzz_font);
300 return harfbuzz_font;
301 }
302
303 // Returns true if characters of |block_code| may trigger font fallback.
IsUnusualBlockCode(UBlockCode block_code)304 bool IsUnusualBlockCode(UBlockCode block_code) {
305 return block_code == UBLOCK_GEOMETRIC_SHAPES ||
306 block_code == UBLOCK_MISCELLANEOUS_SYMBOLS;
307 }
308
IsBracket(UChar32 character)309 bool IsBracket(UChar32 character) {
310 static const char kBrackets[] = { '(', ')', '{', '}', '<', '>', };
311 static const char* kBracketsEnd = kBrackets + arraysize(kBrackets);
312 return std::find(kBrackets, kBracketsEnd, character) != kBracketsEnd;
313 }
314
315 // Returns the boundary between a special and a regular character. Special
316 // characters are brackets or characters that satisfy |IsUnusualBlockCode|.
FindRunBreakingCharacter(const base::string16 & text,size_t run_start,size_t run_break)317 size_t FindRunBreakingCharacter(const base::string16& text,
318 size_t run_start,
319 size_t run_break) {
320 const int32 run_length = static_cast<int32>(run_break - run_start);
321 base::i18n::UTF16CharIterator iter(text.c_str() + run_start, run_length);
322 const UChar32 first_char = iter.get();
323 const UBlockCode first_block = ublock_getCode(first_char);
324 const bool first_block_unusual = IsUnusualBlockCode(first_block);
325 const bool first_bracket = IsBracket(first_char);
326
327 while (iter.Advance() && iter.array_pos() < run_length) {
328 const UChar32 current_char = iter.get();
329 const UBlockCode current_block = ublock_getCode(current_char);
330 const bool block_break = current_block != first_block &&
331 (first_block_unusual || IsUnusualBlockCode(current_block));
332 if (block_break || first_bracket != IsBracket(current_char))
333 return run_start + iter.array_pos();
334 }
335 return run_break;
336 }
337
338 // If the given scripts match, returns the one that isn't USCRIPT_COMMON or
339 // USCRIPT_INHERITED, i.e. the more specific one. Otherwise returns
340 // USCRIPT_INVALID_CODE.
ScriptIntersect(UScriptCode first,UScriptCode second)341 UScriptCode ScriptIntersect(UScriptCode first, UScriptCode second) {
342 if (first == second ||
343 (second > USCRIPT_INVALID_CODE && second <= USCRIPT_INHERITED)) {
344 return first;
345 }
346 if (first > USCRIPT_INVALID_CODE && first <= USCRIPT_INHERITED)
347 return second;
348 return USCRIPT_INVALID_CODE;
349 }
350
351 // Writes the script and the script extensions of the character with the
352 // Unicode |codepoint|. Returns the number of written scripts.
GetScriptExtensions(UChar32 codepoint,UScriptCode * scripts)353 int GetScriptExtensions(UChar32 codepoint, UScriptCode* scripts) {
354 UErrorCode icu_error = U_ZERO_ERROR;
355 // ICU documentation incorrectly states that the result of
356 // |uscript_getScriptExtensions| will contain the regular script property.
357 // Write the character's script property to the first element.
358 scripts[0] = uscript_getScript(codepoint, &icu_error);
359 if (U_FAILURE(icu_error))
360 return 0;
361 // Fill the rest of |scripts| with the extensions.
362 int count = uscript_getScriptExtensions(codepoint, scripts + 1,
363 kMaxScripts - 1, &icu_error);
364 if (U_FAILURE(icu_error))
365 count = 0;
366 return count + 1;
367 }
368
369 // Intersects the script extensions set of |codepoint| with |result| and writes
370 // to |result|, reading and updating |result_size|.
ScriptSetIntersect(UChar32 codepoint,UScriptCode * result,size_t * result_size)371 void ScriptSetIntersect(UChar32 codepoint,
372 UScriptCode* result,
373 size_t* result_size) {
374 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
375 int count = GetScriptExtensions(codepoint, scripts);
376
377 size_t out_size = 0;
378
379 for (size_t i = 0; i < *result_size; ++i) {
380 for (int j = 0; j < count; ++j) {
381 UScriptCode intersection = ScriptIntersect(result[i], scripts[j]);
382 if (intersection != USCRIPT_INVALID_CODE) {
383 result[out_size++] = intersection;
384 break;
385 }
386 }
387 }
388
389 *result_size = out_size;
390 }
391
392 // Find the longest sequence of characters from 0 and up to |length| that
393 // have at least one common UScriptCode value. Writes the common script value to
394 // |script| and returns the length of the sequence. Takes the characters' script
395 // extensions into account. http://www.unicode.org/reports/tr24/#ScriptX
396 //
397 // Consider 3 characters with the script values {Kana}, {Hira, Kana}, {Kana}.
398 // Without script extensions only the first script in each set would be taken
399 // into account, resulting in 3 runs where 1 would be enough.
400 // TODO(ckocagil): Write a unit test for the case above.
ScriptInterval(const base::string16 & text,size_t start,size_t length,UScriptCode * script)401 int ScriptInterval(const base::string16& text,
402 size_t start,
403 size_t length,
404 UScriptCode* script) {
405 DCHECK_GT(length, 0U);
406
407 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
408
409 base::i18n::UTF16CharIterator char_iterator(text.c_str() + start, length);
410 size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts);
411 *script = scripts[0];
412
413 while (char_iterator.Advance()) {
414 ScriptSetIntersect(char_iterator.get(), scripts, &scripts_size);
415 if (scripts_size == 0U)
416 return char_iterator.array_pos();
417 *script = scripts[0];
418 }
419
420 return length;
421 }
422
423 // A port of hb_icu_script_to_script because harfbuzz on CrOS is built without
424 // hb-icu. See http://crbug.com/356929
ICUScriptToHBScript(UScriptCode script)425 inline hb_script_t ICUScriptToHBScript(UScriptCode script) {
426 if (script == USCRIPT_INVALID_CODE)
427 return HB_SCRIPT_INVALID;
428 return hb_script_from_string(uscript_getShortName(script), -1);
429 }
430
431 // Helper template function for |TextRunHarfBuzz::GetClusterAt()|. |Iterator|
432 // can be a forward or reverse iterator type depending on the text direction.
433 template <class Iterator>
GetClusterAtImpl(size_t pos,Range range,Iterator elements_begin,Iterator elements_end,bool reversed,Range * chars,Range * glyphs)434 void GetClusterAtImpl(size_t pos,
435 Range range,
436 Iterator elements_begin,
437 Iterator elements_end,
438 bool reversed,
439 Range* chars,
440 Range* glyphs) {
441 Iterator element = std::upper_bound(elements_begin, elements_end, pos);
442 chars->set_end(element == elements_end ? range.end() : *element);
443 glyphs->set_end(reversed ? elements_end - element : element - elements_begin);
444
445 DCHECK(element != elements_begin);
446 while (--element != elements_begin && *element == *(element - 1));
447 chars->set_start(*element);
448 glyphs->set_start(
449 reversed ? elements_end - element : element - elements_begin);
450 if (reversed)
451 *glyphs = Range(glyphs->end(), glyphs->start());
452
453 DCHECK(!chars->is_reversed());
454 DCHECK(!chars->is_empty());
455 DCHECK(!glyphs->is_reversed());
456 DCHECK(!glyphs->is_empty());
457 }
458
459 } // namespace
460
461 namespace internal {
462
TextRunHarfBuzz()463 TextRunHarfBuzz::TextRunHarfBuzz()
464 : width(0.0f),
465 preceding_run_widths(0.0f),
466 is_rtl(false),
467 level(0),
468 script(USCRIPT_INVALID_CODE),
469 glyph_count(static_cast<size_t>(-1)),
470 font_size(0),
471 font_style(0),
472 strike(false),
473 diagonal_strike(false),
474 underline(false) {}
475
~TextRunHarfBuzz()476 TextRunHarfBuzz::~TextRunHarfBuzz() {}
477
GetClusterAt(size_t pos,Range * chars,Range * glyphs) const478 void TextRunHarfBuzz::GetClusterAt(size_t pos,
479 Range* chars,
480 Range* glyphs) const {
481 DCHECK(range.Contains(Range(pos, pos + 1)));
482 DCHECK(chars);
483 DCHECK(glyphs);
484
485 if (glyph_count == 0) {
486 *chars = range;
487 *glyphs = Range();
488 return;
489 }
490
491 if (is_rtl) {
492 GetClusterAtImpl(pos, range, glyph_to_char.rbegin(), glyph_to_char.rend(),
493 true, chars, glyphs);
494 return;
495 }
496
497 GetClusterAtImpl(pos, range, glyph_to_char.begin(), glyph_to_char.end(),
498 false, chars, glyphs);
499 }
500
CharRangeToGlyphRange(const Range & char_range) const501 Range TextRunHarfBuzz::CharRangeToGlyphRange(const Range& char_range) const {
502 DCHECK(range.Contains(char_range));
503 DCHECK(!char_range.is_reversed());
504 DCHECK(!char_range.is_empty());
505
506 Range start_glyphs;
507 Range end_glyphs;
508 Range temp_range;
509 GetClusterAt(char_range.start(), &temp_range, &start_glyphs);
510 GetClusterAt(char_range.end() - 1, &temp_range, &end_glyphs);
511
512 return is_rtl ? Range(end_glyphs.start(), start_glyphs.end()) :
513 Range(start_glyphs.start(), end_glyphs.end());
514 }
515
CountMissingGlyphs() const516 size_t TextRunHarfBuzz::CountMissingGlyphs() const {
517 static const int kMissingGlyphId = 0;
518 size_t missing = 0;
519 for (size_t i = 0; i < glyph_count; ++i)
520 missing += (glyphs[i] == kMissingGlyphId) ? 1 : 0;
521 return missing;
522 }
523
GetGraphemeBounds(base::i18n::BreakIterator * grapheme_iterator,size_t text_index)524 Range TextRunHarfBuzz::GetGraphemeBounds(
525 base::i18n::BreakIterator* grapheme_iterator,
526 size_t text_index) {
527 DCHECK_LT(text_index, range.end());
528 // TODO(msw): Support floating point grapheme bounds.
529 const int preceding_run_widths_int = SkScalarRoundToInt(preceding_run_widths);
530 if (glyph_count == 0)
531 return Range(preceding_run_widths_int, preceding_run_widths_int + width);
532
533 Range chars;
534 Range glyphs;
535 GetClusterAt(text_index, &chars, &glyphs);
536 const int cluster_begin_x = SkScalarRoundToInt(positions[glyphs.start()].x());
537 const int cluster_end_x = glyphs.end() < glyph_count ?
538 SkScalarRoundToInt(positions[glyphs.end()].x()) : width;
539
540 // A cluster consists of a number of code points and corresponds to a number
541 // of glyphs that should be drawn together. A cluster can contain multiple
542 // graphemes. In order to place the cursor at a grapheme boundary inside the
543 // cluster, we simply divide the cluster width by the number of graphemes.
544 if (chars.length() > 1 && grapheme_iterator) {
545 int before = 0;
546 int total = 0;
547 for (size_t i = chars.start(); i < chars.end(); ++i) {
548 if (grapheme_iterator->IsGraphemeBoundary(i)) {
549 if (i < text_index)
550 ++before;
551 ++total;
552 }
553 }
554 DCHECK_GT(total, 0);
555 if (total > 1) {
556 if (is_rtl)
557 before = total - before - 1;
558 DCHECK_GE(before, 0);
559 DCHECK_LT(before, total);
560 const int cluster_width = cluster_end_x - cluster_begin_x;
561 const int grapheme_begin_x = cluster_begin_x + static_cast<int>(0.5f +
562 cluster_width * before / static_cast<float>(total));
563 const int grapheme_end_x = cluster_begin_x + static_cast<int>(0.5f +
564 cluster_width * (before + 1) / static_cast<float>(total));
565 return Range(preceding_run_widths_int + grapheme_begin_x,
566 preceding_run_widths_int + grapheme_end_x);
567 }
568 }
569
570 return Range(preceding_run_widths_int + cluster_begin_x,
571 preceding_run_widths_int + cluster_end_x);
572 }
573
574 } // namespace internal
575
RenderTextHarfBuzz()576 RenderTextHarfBuzz::RenderTextHarfBuzz()
577 : RenderText(),
578 needs_layout_(false) {
579 set_truncate_length(kMaxTextLength);
580 }
581
~RenderTextHarfBuzz()582 RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
583
GetStringSize()584 Size RenderTextHarfBuzz::GetStringSize() {
585 const SizeF size_f = GetStringSizeF();
586 return Size(std::ceil(size_f.width()), size_f.height());
587 }
588
GetStringSizeF()589 SizeF RenderTextHarfBuzz::GetStringSizeF() {
590 EnsureLayout();
591 return lines()[0].size;
592 }
593
FindCursorPosition(const Point & point)594 SelectionModel RenderTextHarfBuzz::FindCursorPosition(const Point& point) {
595 EnsureLayout();
596
597 int x = ToTextPoint(point).x();
598 int offset = 0;
599 size_t run_index = GetRunContainingXCoord(x, &offset);
600 if (run_index >= runs_.size())
601 return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT);
602 const internal::TextRunHarfBuzz& run = *runs_[run_index];
603
604 for (size_t i = 0; i < run.glyph_count; ++i) {
605 const SkScalar end =
606 i + 1 == run.glyph_count ? run.width : run.positions[i + 1].x();
607 const SkScalar middle = (end + run.positions[i].x()) / 2;
608
609 if (offset < middle) {
610 return SelectionModel(LayoutIndexToTextIndex(
611 run.glyph_to_char[i] + (run.is_rtl ? 1 : 0)),
612 (run.is_rtl ? CURSOR_BACKWARD : CURSOR_FORWARD));
613 }
614 if (offset < end) {
615 return SelectionModel(LayoutIndexToTextIndex(
616 run.glyph_to_char[i] + (run.is_rtl ? 0 : 1)),
617 (run.is_rtl ? CURSOR_FORWARD : CURSOR_BACKWARD));
618 }
619 }
620 return EdgeSelectionModel(CURSOR_RIGHT);
621 }
622
GetFontSpansForTesting()623 std::vector<RenderText::FontSpan> RenderTextHarfBuzz::GetFontSpansForTesting() {
624 EnsureLayout();
625
626 std::vector<RenderText::FontSpan> spans;
627 for (size_t i = 0; i < runs_.size(); ++i) {
628 SkString family_name;
629 runs_[i]->skia_face->getFamilyName(&family_name);
630 Font font(family_name.c_str(), runs_[i]->font_size);
631 spans.push_back(RenderText::FontSpan(font,
632 Range(LayoutIndexToTextIndex(runs_[i]->range.start()),
633 LayoutIndexToTextIndex(runs_[i]->range.end()))));
634 }
635
636 return spans;
637 }
638
GetGlyphBounds(size_t index)639 Range RenderTextHarfBuzz::GetGlyphBounds(size_t index) {
640 EnsureLayout();
641 const size_t run_index =
642 GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD));
643 // Return edge bounds if the index is invalid or beyond the layout text size.
644 if (run_index >= runs_.size())
645 return Range(GetStringSize().width());
646 const size_t layout_index = TextIndexToLayoutIndex(index);
647 internal::TextRunHarfBuzz* run = runs_[run_index];
648 Range bounds = run->GetGraphemeBounds(grapheme_iterator_.get(), layout_index);
649 return run->is_rtl ? Range(bounds.end(), bounds.start()) : bounds;
650 }
651
GetLayoutTextBaseline()652 int RenderTextHarfBuzz::GetLayoutTextBaseline() {
653 EnsureLayout();
654 return lines()[0].baseline;
655 }
656
AdjacentCharSelectionModel(const SelectionModel & selection,VisualCursorDirection direction)657 SelectionModel RenderTextHarfBuzz::AdjacentCharSelectionModel(
658 const SelectionModel& selection,
659 VisualCursorDirection direction) {
660 DCHECK(!needs_layout_);
661 internal::TextRunHarfBuzz* run;
662 size_t run_index = GetRunContainingCaret(selection);
663 if (run_index >= runs_.size()) {
664 // The cursor is not in any run: we're at the visual and logical edge.
665 SelectionModel edge = EdgeSelectionModel(direction);
666 if (edge.caret_pos() == selection.caret_pos())
667 return edge;
668 int visual_index = (direction == CURSOR_RIGHT) ? 0 : runs_.size() - 1;
669 run = runs_[visual_to_logical_[visual_index]];
670 } else {
671 // If the cursor is moving within the current run, just move it by one
672 // grapheme in the appropriate direction.
673 run = runs_[run_index];
674 size_t caret = selection.caret_pos();
675 bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
676 if (forward_motion) {
677 if (caret < LayoutIndexToTextIndex(run->range.end())) {
678 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
679 return SelectionModel(caret, CURSOR_BACKWARD);
680 }
681 } else {
682 if (caret > LayoutIndexToTextIndex(run->range.start())) {
683 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
684 return SelectionModel(caret, CURSOR_FORWARD);
685 }
686 }
687 // The cursor is at the edge of a run; move to the visually adjacent run.
688 int visual_index = logical_to_visual_[run_index];
689 visual_index += (direction == CURSOR_LEFT) ? -1 : 1;
690 if (visual_index < 0 || visual_index >= static_cast<int>(runs_.size()))
691 return EdgeSelectionModel(direction);
692 run = runs_[visual_to_logical_[visual_index]];
693 }
694 bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
695 return forward_motion ? FirstSelectionModelInsideRun(run) :
696 LastSelectionModelInsideRun(run);
697 }
698
AdjacentWordSelectionModel(const SelectionModel & selection,VisualCursorDirection direction)699 SelectionModel RenderTextHarfBuzz::AdjacentWordSelectionModel(
700 const SelectionModel& selection,
701 VisualCursorDirection direction) {
702 if (obscured())
703 return EdgeSelectionModel(direction);
704
705 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
706 bool success = iter.Init();
707 DCHECK(success);
708 if (!success)
709 return selection;
710
711 // Match OS specific word break behavior.
712 #if defined(OS_WIN)
713 size_t pos;
714 if (direction == CURSOR_RIGHT) {
715 pos = std::min(selection.caret_pos() + 1, text().length());
716 while (iter.Advance()) {
717 pos = iter.pos();
718 if (iter.IsWord() && pos > selection.caret_pos())
719 break;
720 }
721 } else { // direction == CURSOR_LEFT
722 // Notes: We always iterate words from the beginning.
723 // This is probably fast enough for our usage, but we may
724 // want to modify WordIterator so that it can start from the
725 // middle of string and advance backwards.
726 pos = std::max<int>(selection.caret_pos() - 1, 0);
727 while (iter.Advance()) {
728 if (iter.IsWord()) {
729 size_t begin = iter.pos() - iter.GetString().length();
730 if (begin == selection.caret_pos()) {
731 // The cursor is at the beginning of a word.
732 // Move to previous word.
733 break;
734 } else if (iter.pos() >= selection.caret_pos()) {
735 // The cursor is in the middle or at the end of a word.
736 // Move to the top of current word.
737 pos = begin;
738 break;
739 }
740 pos = iter.pos() - iter.GetString().length();
741 }
742 }
743 }
744 return SelectionModel(pos, CURSOR_FORWARD);
745 #else
746 SelectionModel cur(selection);
747 for (;;) {
748 cur = AdjacentCharSelectionModel(cur, direction);
749 size_t run = GetRunContainingCaret(cur);
750 if (run == runs_.size())
751 break;
752 const bool is_forward = runs_[run]->is_rtl == (direction == CURSOR_LEFT);
753 size_t cursor = cur.caret_pos();
754 if (is_forward ? iter.IsEndOfWord(cursor) : iter.IsStartOfWord(cursor))
755 break;
756 }
757 return cur;
758 #endif
759 }
760
GetSubstringBounds(const Range & range)761 std::vector<Rect> RenderTextHarfBuzz::GetSubstringBounds(const Range& range) {
762 DCHECK(!needs_layout_);
763 DCHECK(Range(0, text().length()).Contains(range));
764 Range layout_range(TextIndexToLayoutIndex(range.start()),
765 TextIndexToLayoutIndex(range.end()));
766 DCHECK(Range(0, GetLayoutText().length()).Contains(layout_range));
767
768 std::vector<Rect> rects;
769 if (layout_range.is_empty())
770 return rects;
771 std::vector<Range> bounds;
772
773 // Add a Range for each run/selection intersection.
774 for (size_t i = 0; i < runs_.size(); ++i) {
775 internal::TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
776 Range intersection = run->range.Intersect(layout_range);
777 if (!intersection.IsValid())
778 continue;
779 DCHECK(!intersection.is_reversed());
780 const Range leftmost_character_x = run->GetGraphemeBounds(
781 grapheme_iterator_.get(),
782 run->is_rtl ? intersection.end() - 1 : intersection.start());
783 const Range rightmost_character_x = run->GetGraphemeBounds(
784 grapheme_iterator_.get(),
785 run->is_rtl ? intersection.start() : intersection.end() - 1);
786 Range range_x(leftmost_character_x.start(), rightmost_character_x.end());
787 DCHECK(!range_x.is_reversed());
788 if (range_x.is_empty())
789 continue;
790
791 // Union this with the last range if they're adjacent.
792 DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin());
793 if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) {
794 range_x = Range(bounds.back().GetMin(), range_x.GetMax());
795 bounds.pop_back();
796 }
797 bounds.push_back(range_x);
798 }
799 for (size_t i = 0; i < bounds.size(); ++i) {
800 std::vector<Rect> current_rects = TextBoundsToViewBounds(bounds[i]);
801 rects.insert(rects.end(), current_rects.begin(), current_rects.end());
802 }
803 return rects;
804 }
805
TextIndexToLayoutIndex(size_t index) const806 size_t RenderTextHarfBuzz::TextIndexToLayoutIndex(size_t index) const {
807 DCHECK_LE(index, text().length());
808 ptrdiff_t i = obscured() ? UTF16IndexToOffset(text(), 0, index) : index;
809 CHECK_GE(i, 0);
810 // Clamp layout indices to the length of the text actually used for layout.
811 return std::min<size_t>(GetLayoutText().length(), i);
812 }
813
LayoutIndexToTextIndex(size_t index) const814 size_t RenderTextHarfBuzz::LayoutIndexToTextIndex(size_t index) const {
815 if (!obscured())
816 return index;
817
818 DCHECK_LE(index, GetLayoutText().length());
819 const size_t text_index = UTF16OffsetToIndex(text(), 0, index);
820 DCHECK_LE(text_index, text().length());
821 return text_index;
822 }
823
IsValidCursorIndex(size_t index)824 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index) {
825 if (index == 0 || index == text().length())
826 return true;
827 if (!IsValidLogicalIndex(index))
828 return false;
829 EnsureLayout();
830 return !grapheme_iterator_ || grapheme_iterator_->IsGraphemeBoundary(index);
831 }
832
ResetLayout()833 void RenderTextHarfBuzz::ResetLayout() {
834 needs_layout_ = true;
835 }
836
EnsureLayout()837 void RenderTextHarfBuzz::EnsureLayout() {
838 if (needs_layout_) {
839 runs_.clear();
840 grapheme_iterator_.reset();
841
842 if (!GetLayoutText().empty()) {
843 grapheme_iterator_.reset(new base::i18n::BreakIterator(GetLayoutText(),
844 base::i18n::BreakIterator::BREAK_CHARACTER));
845 if (!grapheme_iterator_->Init())
846 grapheme_iterator_.reset();
847
848 ItemizeText();
849
850 for (size_t i = 0; i < runs_.size(); ++i)
851 ShapeRun(runs_[i]);
852
853 // Precalculate run width information.
854 float preceding_run_widths = 0.0f;
855 for (size_t i = 0; i < runs_.size(); ++i) {
856 internal::TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
857 run->preceding_run_widths = preceding_run_widths;
858 preceding_run_widths += run->width;
859 }
860 }
861
862 needs_layout_ = false;
863 std::vector<internal::Line> empty_lines;
864 set_lines(&empty_lines);
865 }
866
867 if (lines().empty()) {
868 std::vector<internal::Line> lines;
869 lines.push_back(internal::Line());
870 lines[0].baseline = font_list().GetBaseline();
871 lines[0].size.set_height(font_list().GetHeight());
872
873 int current_x = 0;
874 SkPaint paint;
875
876 for (size_t i = 0; i < runs_.size(); ++i) {
877 const internal::TextRunHarfBuzz& run = *runs_[visual_to_logical_[i]];
878 internal::LineSegment segment;
879 segment.x_range = Range(current_x, current_x + run.width);
880 segment.char_range = run.range;
881 segment.run = i;
882 lines[0].segments.push_back(segment);
883
884 paint.setTypeface(run.skia_face.get());
885 paint.setTextSize(run.font_size);
886 SkPaint::FontMetrics metrics;
887 paint.getFontMetrics(&metrics);
888
889 lines[0].size.set_width(lines[0].size.width() + run.width);
890 lines[0].size.set_height(std::max(lines[0].size.height(),
891 metrics.fDescent - metrics.fAscent));
892 lines[0].baseline = std::max(lines[0].baseline,
893 SkScalarRoundToInt(-metrics.fAscent));
894 }
895
896 set_lines(&lines);
897 }
898 }
899
DrawVisualText(Canvas * canvas)900 void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) {
901 DCHECK(!needs_layout_);
902 internal::SkiaTextRenderer renderer(canvas);
903 ApplyFadeEffects(&renderer);
904 ApplyTextShadows(&renderer);
905 ApplyCompositionAndSelectionStyles();
906
907 int current_x = 0;
908 const Vector2d line_offset = GetLineOffset(0);
909 for (size_t i = 0; i < runs_.size(); ++i) {
910 const internal::TextRunHarfBuzz& run = *runs_[visual_to_logical_[i]];
911 renderer.SetTypeface(run.skia_face.get());
912 renderer.SetTextSize(run.font_size);
913 renderer.SetFontRenderParams(run.render_params,
914 background_is_transparent());
915
916 Vector2d origin = line_offset + Vector2d(current_x, lines()[0].baseline);
917 scoped_ptr<SkPoint[]> positions(new SkPoint[run.glyph_count]);
918 for (size_t j = 0; j < run.glyph_count; ++j) {
919 positions[j] = run.positions[j];
920 positions[j].offset(SkIntToScalar(origin.x()), SkIntToScalar(origin.y()));
921 }
922
923 for (BreakList<SkColor>::const_iterator it =
924 colors().GetBreak(run.range.start());
925 it != colors().breaks().end() && it->first < run.range.end();
926 ++it) {
927 const Range intersection = colors().GetRange(it).Intersect(run.range);
928 const Range colored_glyphs = run.CharRangeToGlyphRange(intersection);
929 // The range may be empty if a portion of a multi-character grapheme is
930 // selected, yielding two colors for a single glyph. For now, this just
931 // paints the glyph with a single style, but it should paint it twice,
932 // clipped according to selection bounds. See http://crbug.com/366786
933 if (colored_glyphs.is_empty())
934 continue;
935
936 renderer.SetForegroundColor(it->second);
937 renderer.DrawPosText(&positions[colored_glyphs.start()],
938 &run.glyphs[colored_glyphs.start()],
939 colored_glyphs.length());
940 int width = (colored_glyphs.end() == run.glyph_count ? run.width :
941 run.positions[colored_glyphs.end()].x()) -
942 run.positions[colored_glyphs.start()].x();
943 renderer.DrawDecorations(origin.x(), origin.y(), width, run.underline,
944 run.strike, run.diagonal_strike);
945 }
946
947 current_x += run.width;
948 }
949
950 renderer.EndDiagonalStrike();
951
952 UndoCompositionAndSelectionStyles();
953 }
954
GetRunContainingCaret(const SelectionModel & caret) const955 size_t RenderTextHarfBuzz::GetRunContainingCaret(
956 const SelectionModel& caret) const {
957 DCHECK(!needs_layout_);
958 size_t layout_position = TextIndexToLayoutIndex(caret.caret_pos());
959 LogicalCursorDirection affinity = caret.caret_affinity();
960 for (size_t run = 0; run < runs_.size(); ++run) {
961 if (RangeContainsCaret(runs_[run]->range, layout_position, affinity))
962 return run;
963 }
964 return runs_.size();
965 }
966
GetRunContainingXCoord(int x,int * offset) const967 size_t RenderTextHarfBuzz::GetRunContainingXCoord(int x, int* offset) const {
968 DCHECK(!needs_layout_);
969 if (x < 0)
970 return runs_.size();
971 // Find the text run containing the argument point (assumed already offset).
972 int current_x = 0;
973 for (size_t i = 0; i < runs_.size(); ++i) {
974 size_t run = visual_to_logical_[i];
975 current_x += runs_[run]->width;
976 if (x < current_x) {
977 *offset = x - (current_x - runs_[run]->width);
978 return run;
979 }
980 }
981 return runs_.size();
982 }
983
FirstSelectionModelInsideRun(const internal::TextRunHarfBuzz * run)984 SelectionModel RenderTextHarfBuzz::FirstSelectionModelInsideRun(
985 const internal::TextRunHarfBuzz* run) {
986 size_t position = LayoutIndexToTextIndex(run->range.start());
987 position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD);
988 return SelectionModel(position, CURSOR_BACKWARD);
989 }
990
LastSelectionModelInsideRun(const internal::TextRunHarfBuzz * run)991 SelectionModel RenderTextHarfBuzz::LastSelectionModelInsideRun(
992 const internal::TextRunHarfBuzz* run) {
993 size_t position = LayoutIndexToTextIndex(run->range.end());
994 position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD);
995 return SelectionModel(position, CURSOR_FORWARD);
996 }
997
ItemizeText()998 void RenderTextHarfBuzz::ItemizeText() {
999 const base::string16& text = GetLayoutText();
1000 const bool is_text_rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT;
1001 DCHECK_NE(0U, text.length());
1002
1003 // If ICU fails to itemize the text, we create a run that spans the entire
1004 // text. This is needed because leaving the runs set empty causes some clients
1005 // to misbehave since they expect non-zero text metrics from a non-empty text.
1006 base::i18n::BiDiLineIterator bidi_iterator;
1007 if (!bidi_iterator.Open(text, is_text_rtl, false)) {
1008 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
1009 run->range = Range(0, text.length());
1010 runs_.push_back(run);
1011 visual_to_logical_ = logical_to_visual_ = std::vector<int32_t>(1, 0);
1012 return;
1013 }
1014
1015 // Temporarily apply composition underlines and selection colors.
1016 ApplyCompositionAndSelectionStyles();
1017
1018 // Build the list of runs from the script items and ranged styles. Use an
1019 // empty color BreakList to avoid breaking runs at color boundaries.
1020 BreakList<SkColor> empty_colors;
1021 empty_colors.SetMax(text.length());
1022 internal::StyleIterator style(empty_colors, styles());
1023
1024 for (size_t run_break = 0; run_break < text.length();) {
1025 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
1026 run->range.set_start(run_break);
1027 run->font_style = (style.style(BOLD) ? Font::BOLD : 0) |
1028 (style.style(ITALIC) ? Font::ITALIC : 0);
1029 run->strike = style.style(STRIKE);
1030 run->diagonal_strike = style.style(DIAGONAL_STRIKE);
1031 run->underline = style.style(UNDERLINE);
1032
1033 int32 script_item_break = 0;
1034 bidi_iterator.GetLogicalRun(run_break, &script_item_break, &run->level);
1035 // Odd BiDi embedding levels correspond to RTL runs.
1036 run->is_rtl = (run->level % 2) == 1;
1037 // Find the length and script of this script run.
1038 script_item_break = ScriptInterval(text, run_break,
1039 script_item_break - run_break, &run->script) + run_break;
1040
1041 // Find the next break and advance the iterators as needed.
1042 run_break = std::min(static_cast<size_t>(script_item_break),
1043 TextIndexToLayoutIndex(style.GetRange().end()));
1044
1045 // Break runs at certain characters that need to be rendered separately to
1046 // prevent either an unusual character from forcing a fallback font on the
1047 // entire run, or brackets from being affected by a fallback font.
1048 // http://crbug.com/278913, http://crbug.com/396776
1049 if (run_break > run->range.start())
1050 run_break = FindRunBreakingCharacter(text, run->range.start(), run_break);
1051
1052 DCHECK(IsValidCodePointIndex(text, run_break));
1053 style.UpdatePosition(LayoutIndexToTextIndex(run_break));
1054 run->range.set_end(run_break);
1055
1056 runs_.push_back(run);
1057 }
1058
1059 // Undo the temporarily applied composition underlines and selection colors.
1060 UndoCompositionAndSelectionStyles();
1061
1062 const size_t num_runs = runs_.size();
1063 std::vector<UBiDiLevel> levels(num_runs);
1064 for (size_t i = 0; i < num_runs; ++i)
1065 levels[i] = runs_[i]->level;
1066 visual_to_logical_.resize(num_runs);
1067 ubidi_reorderVisual(&levels[0], num_runs, &visual_to_logical_[0]);
1068 logical_to_visual_.resize(num_runs);
1069 ubidi_reorderLogical(&levels[0], num_runs, &logical_to_visual_[0]);
1070 }
1071
ShapeRun(internal::TextRunHarfBuzz * run)1072 void RenderTextHarfBuzz::ShapeRun(internal::TextRunHarfBuzz* run) {
1073 const Font& primary_font = font_list().GetPrimaryFont();
1074 const std::string primary_font_name = primary_font.GetFontName();
1075 run->font_size = primary_font.GetFontSize();
1076
1077 size_t best_font_missing = std::numeric_limits<size_t>::max();
1078 std::string best_font;
1079 std::string current_font;
1080
1081 // Try shaping with |primary_font|.
1082 if (ShapeRunWithFont(run, primary_font_name)) {
1083 current_font = primary_font_name;
1084 size_t current_missing = run->CountMissingGlyphs();
1085 if (current_missing == 0)
1086 return;
1087 if (current_missing < best_font_missing) {
1088 best_font_missing = current_missing;
1089 best_font = current_font;
1090 }
1091 }
1092
1093 #if defined(OS_WIN)
1094 Font uniscribe_font;
1095 const base::char16* run_text = &(GetLayoutText()[run->range.start()]);
1096 if (GetUniscribeFallbackFont(primary_font, run_text, run->range.length(),
1097 &uniscribe_font) &&
1098 ShapeRunWithFont(run, uniscribe_font.GetFontName())) {
1099 current_font = uniscribe_font.GetFontName();
1100 size_t current_missing = run->CountMissingGlyphs();
1101 if (current_missing == 0)
1102 return;
1103 if (current_missing < best_font_missing) {
1104 best_font_missing = current_missing;
1105 best_font = current_font;
1106 }
1107 }
1108 #endif
1109
1110 // Try shaping with the fonts in the fallback list except the first, which is
1111 // |primary_font|.
1112 std::vector<std::string> fonts = GetFallbackFontFamilies(primary_font_name);
1113 for (size_t i = 1; i < fonts.size(); ++i) {
1114 if (!ShapeRunWithFont(run, fonts[i]))
1115 continue;
1116 current_font = fonts[i];
1117 size_t current_missing = run->CountMissingGlyphs();
1118 if (current_missing == 0)
1119 return;
1120 if (current_missing < best_font_missing) {
1121 best_font_missing = current_missing;
1122 best_font = current_font;
1123 }
1124 }
1125
1126 if (!best_font.empty() &&
1127 (best_font == current_font || ShapeRunWithFont(run, best_font))) {
1128 return;
1129 }
1130
1131 run->glyph_count = 0;
1132 run->width = 0.0f;
1133 }
1134
ShapeRunWithFont(internal::TextRunHarfBuzz * run,const std::string & font_family)1135 bool RenderTextHarfBuzz::ShapeRunWithFont(internal::TextRunHarfBuzz* run,
1136 const std::string& font_family) {
1137 const base::string16& text = GetLayoutText();
1138 skia::RefPtr<SkTypeface> skia_face =
1139 internal::CreateSkiaTypeface(font_family, run->font_style);
1140 if (skia_face == NULL)
1141 return false;
1142 run->skia_face = skia_face;
1143 FontRenderParamsQuery query(false);
1144 query.families.push_back(font_family);
1145 query.pixel_size = run->font_size;
1146 query.style = run->font_style;
1147 run->render_params = GetFontRenderParams(query, NULL);
1148 hb_font_t* harfbuzz_font = CreateHarfBuzzFont(run->skia_face.get(),
1149 run->font_size, run->render_params, background_is_transparent());
1150
1151 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
1152 // buffer holds our text, run information to be used by the shaping engine,
1153 // and the resulting glyph data.
1154 hb_buffer_t* buffer = hb_buffer_create();
1155 hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16*>(text.c_str()),
1156 text.length(), run->range.start(), run->range.length());
1157 hb_buffer_set_script(buffer, ICUScriptToHBScript(run->script));
1158 hb_buffer_set_direction(buffer,
1159 run->is_rtl ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
1160 // TODO(ckocagil): Should we determine the actual language?
1161 hb_buffer_set_language(buffer, hb_language_get_default());
1162
1163 // Shape the text.
1164 hb_shape(harfbuzz_font, buffer, NULL, 0);
1165
1166 // Populate the run fields with the resulting glyph data in the buffer.
1167 unsigned int glyph_count = 0;
1168 hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(buffer, &glyph_count);
1169 run->glyph_count = glyph_count;
1170 hb_glyph_position_t* hb_positions =
1171 hb_buffer_get_glyph_positions(buffer, NULL);
1172 run->glyphs.reset(new uint16[run->glyph_count]);
1173 run->glyph_to_char.resize(run->glyph_count);
1174 run->positions.reset(new SkPoint[run->glyph_count]);
1175 run->width = 0.0f;
1176 for (size_t i = 0; i < run->glyph_count; ++i) {
1177 run->glyphs[i] = infos[i].codepoint;
1178 run->glyph_to_char[i] = infos[i].cluster;
1179 const int x_offset = SkFixedToScalar(hb_positions[i].x_offset);
1180 const int y_offset = SkFixedToScalar(hb_positions[i].y_offset);
1181 run->positions[i].set(run->width + x_offset, -y_offset);
1182 run->width += SkFixedToScalar(hb_positions[i].x_advance);
1183 #if defined(OS_LINUX)
1184 // Match Pango's glyph rounding logic on Linux.
1185 if (!run->render_params.subpixel_positioning)
1186 run->width = std::floor(run->width + 0.5f);
1187 #endif
1188 }
1189
1190 hb_buffer_destroy(buffer);
1191 hb_font_destroy(harfbuzz_font);
1192 return true;
1193 }
1194
1195 } // namespace gfx
1196