Revert of Fix missing GN dependencies. (patchset #4 id:60001 of https://codereview...
[chromium-blink-merge.git] / ui / gfx / render_text_harfbuzz.cc
blob32a9e554f60b47127cef9d426aef71a9f410adfa
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.
5 #include "ui/gfx/render_text_harfbuzz.h"
7 #include <limits>
8 #include <set>
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/profiler/scoped_tracker.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/trace_event/trace_event.h"
17 #include "third_party/harfbuzz-ng/src/hb.h"
18 #include "third_party/icu/source/common/unicode/ubidi.h"
19 #include "third_party/skia/include/core/SkColor.h"
20 #include "third_party/skia/include/core/SkTypeface.h"
21 #include "ui/gfx/canvas.h"
22 #include "ui/gfx/font_fallback.h"
23 #include "ui/gfx/font_render_params.h"
24 #include "ui/gfx/geometry/safe_integer_conversions.h"
25 #include "ui/gfx/harfbuzz_font_skia.h"
26 #include "ui/gfx/range/range_f.h"
27 #include "ui/gfx/utf16_indexing.h"
29 #if defined(OS_WIN)
30 #include "ui/gfx/font_fallback_win.h"
31 #endif
33 using gfx::internal::RoundRangeF;
35 namespace gfx {
37 namespace {
39 // Text length limit. Longer strings are slow and not fully tested.
40 const size_t kMaxTextLength = 10000;
42 // The maximum number of scripts a Unicode character can belong to. This value
43 // is arbitrarily chosen to be a good limit because it is unlikely for a single
44 // character to belong to more scripts.
45 const size_t kMaxScripts = 5;
47 // Returns true if characters of |block_code| may trigger font fallback.
48 // Dingbats and emoticons can be rendered through the color emoji font file,
49 // therefore it needs to be trigerred as fallbacks. See crbug.com/448909
50 bool IsUnusualBlockCode(UBlockCode block_code) {
51 return block_code == UBLOCK_GEOMETRIC_SHAPES ||
52 block_code == UBLOCK_MISCELLANEOUS_SYMBOLS ||
53 block_code == UBLOCK_DINGBATS ||
54 block_code == UBLOCK_EMOTICONS;
57 bool IsBracket(UChar32 character) {
58 static const char kBrackets[] = { '(', ')', '{', '}', '<', '>', };
59 static const char* kBracketsEnd = kBrackets + arraysize(kBrackets);
60 return std::find(kBrackets, kBracketsEnd, character) != kBracketsEnd;
63 // Returns the boundary between a special and a regular character. Special
64 // characters are brackets or characters that satisfy |IsUnusualBlockCode|.
65 size_t FindRunBreakingCharacter(const base::string16& text,
66 size_t run_start,
67 size_t run_break) {
68 const int32 run_length = static_cast<int32>(run_break - run_start);
69 base::i18n::UTF16CharIterator iter(text.c_str() + run_start, run_length);
70 const UChar32 first_char = iter.get();
71 // The newline character should form a single run so that the line breaker
72 // can handle them easily.
73 if (first_char == '\n')
74 return run_start + 1;
76 const UBlockCode first_block = ublock_getCode(first_char);
77 const bool first_block_unusual = IsUnusualBlockCode(first_block);
78 const bool first_bracket = IsBracket(first_char);
80 while (iter.Advance() && iter.array_pos() < run_length) {
81 const UChar32 current_char = iter.get();
82 const UBlockCode current_block = ublock_getCode(current_char);
83 const bool block_break = current_block != first_block &&
84 (first_block_unusual || IsUnusualBlockCode(current_block));
85 if (block_break || current_char == '\n' ||
86 first_bracket != IsBracket(current_char)) {
87 return run_start + iter.array_pos();
90 return run_break;
93 // If the given scripts match, returns the one that isn't USCRIPT_COMMON or
94 // USCRIPT_INHERITED, i.e. the more specific one. Otherwise returns
95 // USCRIPT_INVALID_CODE.
96 UScriptCode ScriptIntersect(UScriptCode first, UScriptCode second) {
97 if (first == second ||
98 (second > USCRIPT_INVALID_CODE && second <= USCRIPT_INHERITED)) {
99 return first;
101 if (first > USCRIPT_INVALID_CODE && first <= USCRIPT_INHERITED)
102 return second;
103 return USCRIPT_INVALID_CODE;
106 // Writes the script and the script extensions of the character with the
107 // Unicode |codepoint|. Returns the number of written scripts.
108 int GetScriptExtensions(UChar32 codepoint, UScriptCode* scripts) {
109 UErrorCode icu_error = U_ZERO_ERROR;
110 // ICU documentation incorrectly states that the result of
111 // |uscript_getScriptExtensions| will contain the regular script property.
112 // Write the character's script property to the first element.
113 scripts[0] = uscript_getScript(codepoint, &icu_error);
114 if (U_FAILURE(icu_error))
115 return 0;
116 // Fill the rest of |scripts| with the extensions.
117 int count = uscript_getScriptExtensions(codepoint, scripts + 1,
118 kMaxScripts - 1, &icu_error);
119 if (U_FAILURE(icu_error))
120 count = 0;
121 return count + 1;
124 // Intersects the script extensions set of |codepoint| with |result| and writes
125 // to |result|, reading and updating |result_size|.
126 void ScriptSetIntersect(UChar32 codepoint,
127 UScriptCode* result,
128 size_t* result_size) {
129 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
130 int count = GetScriptExtensions(codepoint, scripts);
132 size_t out_size = 0;
134 for (size_t i = 0; i < *result_size; ++i) {
135 for (int j = 0; j < count; ++j) {
136 UScriptCode intersection = ScriptIntersect(result[i], scripts[j]);
137 if (intersection != USCRIPT_INVALID_CODE) {
138 result[out_size++] = intersection;
139 break;
144 *result_size = out_size;
147 // Find the longest sequence of characters from 0 and up to |length| that
148 // have at least one common UScriptCode value. Writes the common script value to
149 // |script| and returns the length of the sequence. Takes the characters' script
150 // extensions into account. http://www.unicode.org/reports/tr24/#ScriptX
152 // Consider 3 characters with the script values {Kana}, {Hira, Kana}, {Kana}.
153 // Without script extensions only the first script in each set would be taken
154 // into account, resulting in 3 runs where 1 would be enough.
155 // TODO(ckocagil): Write a unit test for the case above.
156 int ScriptInterval(const base::string16& text,
157 size_t start,
158 size_t length,
159 UScriptCode* script) {
160 DCHECK_GT(length, 0U);
162 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
164 base::i18n::UTF16CharIterator char_iterator(text.c_str() + start, length);
165 size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts);
166 *script = scripts[0];
168 while (char_iterator.Advance()) {
169 ScriptSetIntersect(char_iterator.get(), scripts, &scripts_size);
170 if (scripts_size == 0U)
171 return char_iterator.array_pos();
172 *script = scripts[0];
175 return length;
178 // A port of hb_icu_script_to_script because harfbuzz on CrOS is built without
179 // hb-icu. See http://crbug.com/356929
180 inline hb_script_t ICUScriptToHBScript(UScriptCode script) {
181 if (script == USCRIPT_INVALID_CODE)
182 return HB_SCRIPT_INVALID;
183 return hb_script_from_string(uscript_getShortName(script), -1);
186 // Helper template function for |TextRunHarfBuzz::GetClusterAt()|. |Iterator|
187 // can be a forward or reverse iterator type depending on the text direction.
188 template <class Iterator>
189 void GetClusterAtImpl(size_t pos,
190 Range range,
191 Iterator elements_begin,
192 Iterator elements_end,
193 bool reversed,
194 Range* chars,
195 Range* glyphs) {
196 Iterator element = std::upper_bound(elements_begin, elements_end, pos);
197 chars->set_end(element == elements_end ? range.end() : *element);
198 glyphs->set_end(reversed ? elements_end - element : element - elements_begin);
200 DCHECK(element != elements_begin);
201 while (--element != elements_begin && *element == *(element - 1));
202 chars->set_start(*element);
203 glyphs->set_start(
204 reversed ? elements_end - element : element - elements_begin);
205 if (reversed)
206 *glyphs = Range(glyphs->end(), glyphs->start());
208 DCHECK(!chars->is_reversed());
209 DCHECK(!chars->is_empty());
210 DCHECK(!glyphs->is_reversed());
211 DCHECK(!glyphs->is_empty());
214 // Internal class to generate Line structures. If |multiline| is true, the text
215 // is broken into lines at |words| boundaries such that each line is no longer
216 // than |max_width|. If |multiline| is false, only outputs a single Line from
217 // the given runs. |min_baseline| and |min_height| are the minimum baseline and
218 // height for each line.
219 // TODO(ckocagil): Expose the interface of this class in the header and test
220 // this class directly.
221 class HarfBuzzLineBreaker {
222 public:
223 HarfBuzzLineBreaker(size_t max_width,
224 int min_baseline,
225 float min_height,
226 bool multiline,
227 WordWrapBehavior word_wrap_behavior,
228 const base::string16& text,
229 const BreakList<size_t>* words,
230 const internal::TextRunList& run_list)
231 : max_width_((max_width == 0) ? SK_ScalarMax : SkIntToScalar(max_width)),
232 min_baseline_(min_baseline),
233 min_height_(min_height),
234 multiline_(multiline),
235 word_wrap_behavior_(word_wrap_behavior),
236 text_(text),
237 words_(words),
238 run_list_(run_list),
239 text_x_(0),
240 line_x_(0),
241 max_descent_(0),
242 max_ascent_(0) {
243 DCHECK_EQ(multiline_, (words_ != nullptr));
244 AdvanceLine();
247 // Breaks the run at given |run_index| into Line structs.
248 void AddRun(int run_index) {
249 const internal::TextRunHarfBuzz* run = run_list_.runs()[run_index];
250 base::char16 first_char = text_[run->range.start()];
251 if (multiline_ && first_char == '\n') {
252 AdvanceLine();
253 } else if (multiline_ && (line_x_ + SkFloatToScalar(run->width)) >
254 max_width_) {
255 BreakRun(run_index);
256 } else {
257 AddSegment(run_index, run->range, run->width);
261 // Finishes line breaking and outputs the results. Can be called at most once.
262 void Finalize(std::vector<internal::Line>* lines, SizeF* size) {
263 DCHECK(!lines_.empty());
264 // Add an empty line to finish the line size calculation and remove it.
265 AdvanceLine();
266 lines_.pop_back();
267 *size = total_size_;
268 lines->swap(lines_);
271 private:
272 // A (line index, segment index) pair that specifies a segment in |lines_|.
273 typedef std::pair<size_t, size_t> SegmentHandle;
275 internal::LineSegment* SegmentFromHandle(const SegmentHandle& handle) {
276 return &lines_[handle.first].segments[handle.second];
279 // Breaks a run into segments that fit in the last line in |lines_| and adds
280 // them. Adds a new Line to the back of |lines_| whenever a new segment can't
281 // be added without the Line's width exceeding |max_width_|.
282 void BreakRun(int run_index) {
283 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[run_index]);
284 SkScalar width = 0;
285 size_t next_char = run.range.start();
287 // Break the run until it fits the current line.
288 while (next_char < run.range.end()) {
289 const size_t current_char = next_char;
290 size_t end_char = next_char;
291 const bool skip_line =
292 BreakRunAtWidth(run, current_char, &width, &end_char, &next_char);
293 AddSegment(run_index, Range(current_char, end_char),
294 SkScalarToFloat(width));
295 if (skip_line)
296 AdvanceLine();
300 // Starting from |start_char|, finds a suitable line break position at or
301 // before available width using word break. If the current position is at the
302 // beginning of a line, this function will not roll back to |start_char| and
303 // |*next_char| will be greater than |start_char| (to avoid constructing empty
304 // lines). It stores the end of the segment range to |end_char|, which can be
305 // smaller than |*next_char| for certain word wrapping behavior.
306 // Returns whether to skip the line before |*next_char|.
307 // TODO(ckocagil): We might have to reshape after breaking at ligatures.
308 // See whether resolving the TODO above resolves this too.
309 // TODO(ckocagil): Do not reserve width for whitespace at the end of lines.
310 bool BreakRunAtWidth(const internal::TextRunHarfBuzz& run,
311 size_t start_char,
312 SkScalar* width,
313 size_t* end_char,
314 size_t* next_char) {
315 DCHECK(words_);
316 DCHECK(run.range.Contains(Range(start_char, start_char + 1)));
317 SkScalar available_width = max_width_ - line_x_;
318 BreakList<size_t>::const_iterator word = words_->GetBreak(start_char);
319 BreakList<size_t>::const_iterator next_word = word + 1;
320 // Width from |std::max(word->first, start_char)| to the current character.
321 SkScalar word_width = 0;
322 *width = 0;
324 Range char_range;
325 SkScalar truncated_width = 0;
326 for (size_t i = start_char; i < run.range.end(); i += char_range.length()) {
327 // |word| holds the word boundary at or before |i|, and |next_word| holds
328 // the word boundary right after |i|. Advance both |word| and |next_word|
329 // when |i| reaches |next_word|.
330 if (next_word != words_->breaks().end() && i >= next_word->first) {
331 if (*width > available_width) {
332 DCHECK_NE(WRAP_LONG_WORDS, word_wrap_behavior_);
333 *next_char = i;
334 if (word_wrap_behavior_ != TRUNCATE_LONG_WORDS)
335 *end_char = *next_char;
336 else
337 *width = truncated_width;
338 return true;
340 word = next_word++;
341 word_width = 0;
344 Range glyph_range;
345 run.GetClusterAt(i, &char_range, &glyph_range);
346 DCHECK_LT(0U, char_range.length());
348 SkScalar char_width = ((glyph_range.end() >= run.glyph_count)
349 ? SkFloatToScalar(run.width)
350 : run.positions[glyph_range.end()].x()) -
351 run.positions[glyph_range.start()].x();
353 *width += char_width;
354 word_width += char_width;
356 // TODO(mukai): implement ELIDE_LONG_WORDS.
357 if (*width > available_width) {
358 if (line_x_ != 0 || word_width < *width) {
359 // Roll back one word.
360 *width -= word_width;
361 *next_char = std::max(word->first, start_char);
362 *end_char = *next_char;
363 return true;
364 } else if (word_wrap_behavior_ == WRAP_LONG_WORDS) {
365 if (char_width < *width) {
366 // Roll back one character.
367 *width -= char_width;
368 *next_char = i;
369 } else {
370 // Continue from the next character.
371 *next_char = i + char_range.length();
373 *end_char = *next_char;
374 return true;
376 } else {
377 *end_char = char_range.end();
378 truncated_width = *width;
382 if (word_wrap_behavior_ == TRUNCATE_LONG_WORDS)
383 *width = truncated_width;
384 *end_char = *next_char = run.range.end();
385 return false;
388 // RTL runs are broken in logical order but displayed in visual order. To find
389 // the text-space coordinate (where it would fall in a single-line text)
390 // |x_range| of RTL segments, segment widths are applied in reverse order.
391 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}.
392 void UpdateRTLSegmentRanges() {
393 if (rtl_segments_.empty())
394 return;
395 float x = SegmentFromHandle(rtl_segments_[0])->x_range.start();
396 for (size_t i = rtl_segments_.size(); i > 0; --i) {
397 internal::LineSegment* segment = SegmentFromHandle(rtl_segments_[i - 1]);
398 const float segment_width = segment->width;
399 segment->x_range = Range(x, x + segment_width);
400 x += segment_width;
402 rtl_segments_.clear();
405 // Finishes the size calculations of the last Line in |lines_|. Adds a new
406 // Line to the back of |lines_|.
407 void AdvanceLine() {
408 if (!lines_.empty()) {
409 internal::Line* line = &lines_.back();
410 std::sort(line->segments.begin(), line->segments.end(),
411 [this](const internal::LineSegment& s1,
412 const internal::LineSegment& s2) -> bool {
413 return run_list_.logical_to_visual(s1.run) <
414 run_list_.logical_to_visual(s2.run);
416 line->size.set_height(std::max(min_height_, max_descent_ + max_ascent_));
417 line->baseline =
418 std::max(min_baseline_, SkScalarRoundToInt(max_ascent_));
419 line->preceding_heights = std::ceil(total_size_.height());
420 total_size_.set_height(total_size_.height() + line->size.height());
421 total_size_.set_width(std::max(total_size_.width(), line->size.width()));
423 max_descent_ = 0;
424 max_ascent_ = 0;
425 line_x_ = 0;
426 lines_.push_back(internal::Line());
429 // Adds a new segment with the given properties to |lines_.back()|.
430 void AddSegment(int run_index, Range char_range, float width) {
431 if (char_range.is_empty()) {
432 DCHECK_EQ(0, width);
433 return;
435 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[run_index]);
437 internal::LineSegment segment;
438 segment.run = run_index;
439 segment.char_range = char_range;
440 segment.x_range = Range(
441 SkScalarCeilToInt(text_x_),
442 SkScalarCeilToInt(text_x_ + SkFloatToScalar(width)));
443 segment.width = width;
445 internal::Line* line = &lines_.back();
446 line->segments.push_back(segment);
448 SkPaint paint;
449 paint.setTypeface(run.skia_face.get());
450 paint.setTextSize(SkIntToScalar(run.font_size));
451 paint.setAntiAlias(run.render_params.antialiasing);
452 SkPaint::FontMetrics metrics;
453 paint.getFontMetrics(&metrics);
455 line->size.set_width(line->size.width() + width);
456 // TODO(dschuyler): Account for stylized baselines in string sizing.
457 max_descent_ = std::max(max_descent_, metrics.fDescent);
458 // fAscent is always negative.
459 max_ascent_ = std::max(max_ascent_, -metrics.fAscent);
461 if (run.is_rtl) {
462 rtl_segments_.push_back(
463 SegmentHandle(lines_.size() - 1, line->segments.size() - 1));
464 // If this is the last segment of an RTL run, reprocess the text-space x
465 // ranges of all segments from the run.
466 if (char_range.end() == run.range.end())
467 UpdateRTLSegmentRanges();
469 text_x_ += SkFloatToScalar(width);
470 line_x_ += SkFloatToScalar(width);
473 const SkScalar max_width_;
474 const int min_baseline_;
475 const float min_height_;
476 const bool multiline_;
477 const WordWrapBehavior word_wrap_behavior_;
478 const base::string16& text_;
479 const BreakList<size_t>* const words_;
480 const internal::TextRunList& run_list_;
482 // Stores the resulting lines.
483 std::vector<internal::Line> lines_;
485 // Text space and line space x coordinates of the next segment to be added.
486 SkScalar text_x_;
487 SkScalar line_x_;
489 float max_descent_;
490 float max_ascent_;
492 // Size of the multiline text, not including the currently processed line.
493 SizeF total_size_;
495 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
496 std::vector<SegmentHandle> rtl_segments_;
498 DISALLOW_COPY_AND_ASSIGN(HarfBuzzLineBreaker);
501 // Function object for case insensitive string comparison.
502 struct CaseInsensitiveCompare {
503 bool operator() (const std::string& a, const std::string& b) const {
504 return base::strncasecmp(a.c_str(), b.c_str(), b.length()) < 0;
508 } // namespace
510 namespace internal {
512 Range RoundRangeF(const RangeF& range_f) {
513 return Range(std::floor(range_f.start() + 0.5f),
514 std::floor(range_f.end() + 0.5f));
517 TextRunHarfBuzz::TextRunHarfBuzz()
518 : width(0.0f),
519 preceding_run_widths(0.0f),
520 is_rtl(false),
521 level(0),
522 script(USCRIPT_INVALID_CODE),
523 glyph_count(static_cast<size_t>(-1)),
524 font_size(0),
525 baseline_offset(0),
526 baseline_type(0),
527 font_style(0),
528 strike(false),
529 diagonal_strike(false),
530 underline(false) {
533 TextRunHarfBuzz::~TextRunHarfBuzz() {}
535 void TextRunHarfBuzz::GetClusterAt(size_t pos,
536 Range* chars,
537 Range* glyphs) const {
538 DCHECK(range.Contains(Range(pos, pos + 1)));
539 DCHECK(chars);
540 DCHECK(glyphs);
542 if (glyph_count == 0) {
543 *chars = range;
544 *glyphs = Range();
545 return;
548 if (is_rtl) {
549 GetClusterAtImpl(pos, range, glyph_to_char.rbegin(), glyph_to_char.rend(),
550 true, chars, glyphs);
551 return;
554 GetClusterAtImpl(pos, range, glyph_to_char.begin(), glyph_to_char.end(),
555 false, chars, glyphs);
558 Range TextRunHarfBuzz::CharRangeToGlyphRange(const Range& char_range) const {
559 DCHECK(range.Contains(char_range));
560 DCHECK(!char_range.is_reversed());
561 DCHECK(!char_range.is_empty());
563 Range start_glyphs;
564 Range end_glyphs;
565 Range temp_range;
566 GetClusterAt(char_range.start(), &temp_range, &start_glyphs);
567 GetClusterAt(char_range.end() - 1, &temp_range, &end_glyphs);
569 return is_rtl ? Range(end_glyphs.start(), start_glyphs.end()) :
570 Range(start_glyphs.start(), end_glyphs.end());
573 size_t TextRunHarfBuzz::CountMissingGlyphs() const {
574 static const int kMissingGlyphId = 0;
575 size_t missing = 0;
576 for (size_t i = 0; i < glyph_count; ++i)
577 missing += (glyphs[i] == kMissingGlyphId) ? 1 : 0;
578 return missing;
581 RangeF TextRunHarfBuzz::GetGraphemeBounds(
582 base::i18n::BreakIterator* grapheme_iterator,
583 size_t text_index) {
584 DCHECK_LT(text_index, range.end());
585 if (glyph_count == 0)
586 return RangeF(preceding_run_widths, preceding_run_widths + width);
588 Range chars;
589 Range glyphs;
590 GetClusterAt(text_index, &chars, &glyphs);
591 const float cluster_begin_x = positions[glyphs.start()].x();
592 const float cluster_end_x = glyphs.end() < glyph_count ?
593 positions[glyphs.end()].x() : SkFloatToScalar(width);
595 // A cluster consists of a number of code points and corresponds to a number
596 // of glyphs that should be drawn together. A cluster can contain multiple
597 // graphemes. In order to place the cursor at a grapheme boundary inside the
598 // cluster, we simply divide the cluster width by the number of graphemes.
599 if (chars.length() > 1 && grapheme_iterator) {
600 int before = 0;
601 int total = 0;
602 for (size_t i = chars.start(); i < chars.end(); ++i) {
603 if (grapheme_iterator->IsGraphemeBoundary(i)) {
604 if (i < text_index)
605 ++before;
606 ++total;
609 DCHECK_GT(total, 0);
610 if (total > 1) {
611 if (is_rtl)
612 before = total - before - 1;
613 DCHECK_GE(before, 0);
614 DCHECK_LT(before, total);
615 const int cluster_width = cluster_end_x - cluster_begin_x;
616 const int grapheme_begin_x = cluster_begin_x + static_cast<int>(0.5f +
617 cluster_width * before / static_cast<float>(total));
618 const int grapheme_end_x = cluster_begin_x + static_cast<int>(0.5f +
619 cluster_width * (before + 1) / static_cast<float>(total));
620 return RangeF(preceding_run_widths + grapheme_begin_x,
621 preceding_run_widths + grapheme_end_x);
625 return RangeF(preceding_run_widths + cluster_begin_x,
626 preceding_run_widths + cluster_end_x);
629 TextRunList::TextRunList() : width_(0.0f) {}
631 TextRunList::~TextRunList() {}
633 void TextRunList::Reset() {
634 runs_.clear();
635 width_ = 0.0f;
638 void TextRunList::InitIndexMap() {
639 if (runs_.size() == 1) {
640 visual_to_logical_ = logical_to_visual_ = std::vector<int32_t>(1, 0);
641 return;
643 const size_t num_runs = runs_.size();
644 std::vector<UBiDiLevel> levels(num_runs);
645 for (size_t i = 0; i < num_runs; ++i)
646 levels[i] = runs_[i]->level;
647 visual_to_logical_.resize(num_runs);
648 ubidi_reorderVisual(&levels[0], num_runs, &visual_to_logical_[0]);
649 logical_to_visual_.resize(num_runs);
650 ubidi_reorderLogical(&levels[0], num_runs, &logical_to_visual_[0]);
653 void TextRunList::ComputePrecedingRunWidths() {
654 // Precalculate run width information.
655 width_ = 0.0f;
656 for (size_t i = 0; i < runs_.size(); ++i) {
657 TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
658 run->preceding_run_widths = width_;
659 width_ += run->width;
663 } // namespace internal
665 RenderTextHarfBuzz::RenderTextHarfBuzz()
666 : RenderText(),
667 update_layout_run_list_(false),
668 update_display_run_list_(false),
669 update_grapheme_iterator_(false),
670 update_display_text_(false),
671 glyph_width_for_test_(0u) {
672 set_truncate_length(kMaxTextLength);
675 RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
677 scoped_ptr<RenderText> RenderTextHarfBuzz::CreateInstanceOfSameType() const {
678 return make_scoped_ptr(new RenderTextHarfBuzz);
681 bool RenderTextHarfBuzz::MultilineSupported() const {
682 return true;
685 const base::string16& RenderTextHarfBuzz::GetDisplayText() {
686 // TODO(oshima): Consider supporting eliding multi-line text.
687 // This requires max_line support first.
688 if (multiline() ||
689 elide_behavior() == NO_ELIDE ||
690 elide_behavior() == FADE_TAIL) {
691 // Call UpdateDisplayText to clear |display_text_| and |text_elided_|
692 // on the RenderText class.
693 UpdateDisplayText(0);
694 update_display_text_ = false;
695 display_run_list_.reset();
696 return layout_text();
699 EnsureLayoutRunList();
700 DCHECK(!update_display_text_);
701 return text_elided() ? display_text() : layout_text();
704 Size RenderTextHarfBuzz::GetStringSize() {
705 const SizeF size_f = GetStringSizeF();
706 return Size(std::ceil(size_f.width()), size_f.height());
709 SizeF RenderTextHarfBuzz::GetStringSizeF() {
710 EnsureLayout();
711 return total_size_;
714 SelectionModel RenderTextHarfBuzz::FindCursorPosition(const Point& point) {
715 EnsureLayout();
717 int x = ToTextPoint(point).x();
718 float offset = 0;
719 size_t run_index = GetRunContainingXCoord(x, &offset);
721 internal::TextRunList* run_list = GetRunList();
722 if (run_index >= run_list->size())
723 return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT);
724 const internal::TextRunHarfBuzz& run = *run_list->runs()[run_index];
725 for (size_t i = 0; i < run.glyph_count; ++i) {
726 const SkScalar end =
727 i + 1 == run.glyph_count ? run.width : run.positions[i + 1].x();
728 const SkScalar middle = (end + run.positions[i].x()) / 2;
730 if (offset < middle) {
731 return SelectionModel(DisplayIndexToTextIndex(
732 run.glyph_to_char[i] + (run.is_rtl ? 1 : 0)),
733 (run.is_rtl ? CURSOR_BACKWARD : CURSOR_FORWARD));
735 if (offset < end) {
736 return SelectionModel(DisplayIndexToTextIndex(
737 run.glyph_to_char[i] + (run.is_rtl ? 0 : 1)),
738 (run.is_rtl ? CURSOR_FORWARD : CURSOR_BACKWARD));
741 return EdgeSelectionModel(CURSOR_RIGHT);
744 std::vector<RenderText::FontSpan> RenderTextHarfBuzz::GetFontSpansForTesting() {
745 EnsureLayout();
747 internal::TextRunList* run_list = GetRunList();
748 std::vector<RenderText::FontSpan> spans;
749 for (auto* run : run_list->runs()) {
750 SkString family_name;
751 run->skia_face->getFamilyName(&family_name);
752 Font font(family_name.c_str(), run->font_size);
753 spans.push_back(RenderText::FontSpan(
754 font,
755 Range(DisplayIndexToTextIndex(run->range.start()),
756 DisplayIndexToTextIndex(run->range.end()))));
759 return spans;
762 Range RenderTextHarfBuzz::GetGlyphBounds(size_t index) {
763 EnsureLayout();
764 const size_t run_index =
765 GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD));
766 internal::TextRunList* run_list = GetRunList();
767 // Return edge bounds if the index is invalid or beyond the layout text size.
768 if (run_index >= run_list->size())
769 return Range(GetStringSize().width());
770 const size_t layout_index = TextIndexToDisplayIndex(index);
771 internal::TextRunHarfBuzz* run = run_list->runs()[run_index];
772 RangeF bounds =
773 run->GetGraphemeBounds(GetGraphemeIterator(), layout_index);
774 // If cursor is enabled, extend the last glyph up to the rightmost cursor
775 // position since clients expect them to be contiguous.
776 if (cursor_enabled() && run_index == run_list->size() - 1 &&
777 index == (run->is_rtl ? run->range.start() : run->range.end() - 1))
778 bounds.set_end(std::ceil(bounds.end()));
779 return RoundRangeF(run->is_rtl ?
780 RangeF(bounds.end(), bounds.start()) : bounds);
783 int RenderTextHarfBuzz::GetDisplayTextBaseline() {
784 EnsureLayout();
785 return lines()[0].baseline;
788 SelectionModel RenderTextHarfBuzz::AdjacentCharSelectionModel(
789 const SelectionModel& selection,
790 VisualCursorDirection direction) {
791 DCHECK(!update_display_run_list_);
793 internal::TextRunList* run_list = GetRunList();
794 internal::TextRunHarfBuzz* run;
796 size_t run_index = GetRunContainingCaret(selection);
797 if (run_index >= run_list->size()) {
798 // The cursor is not in any run: we're at the visual and logical edge.
799 SelectionModel edge = EdgeSelectionModel(direction);
800 if (edge.caret_pos() == selection.caret_pos())
801 return edge;
802 int visual_index = (direction == CURSOR_RIGHT) ? 0 : run_list->size() - 1;
803 run = run_list->runs()[run_list->visual_to_logical(visual_index)];
804 } else {
805 // If the cursor is moving within the current run, just move it by one
806 // grapheme in the appropriate direction.
807 run = run_list->runs()[run_index];
808 size_t caret = selection.caret_pos();
809 bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
810 if (forward_motion) {
811 if (caret < DisplayIndexToTextIndex(run->range.end())) {
812 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
813 return SelectionModel(caret, CURSOR_BACKWARD);
815 } else {
816 if (caret > DisplayIndexToTextIndex(run->range.start())) {
817 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
818 return SelectionModel(caret, CURSOR_FORWARD);
821 // The cursor is at the edge of a run; move to the visually adjacent run.
822 int visual_index = run_list->logical_to_visual(run_index);
823 visual_index += (direction == CURSOR_LEFT) ? -1 : 1;
824 if (visual_index < 0 || visual_index >= static_cast<int>(run_list->size()))
825 return EdgeSelectionModel(direction);
826 run = run_list->runs()[run_list->visual_to_logical(visual_index)];
828 bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
829 return forward_motion ? FirstSelectionModelInsideRun(run) :
830 LastSelectionModelInsideRun(run);
833 SelectionModel RenderTextHarfBuzz::AdjacentWordSelectionModel(
834 const SelectionModel& selection,
835 VisualCursorDirection direction) {
836 if (obscured())
837 return EdgeSelectionModel(direction);
839 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
840 bool success = iter.Init();
841 DCHECK(success);
842 if (!success)
843 return selection;
845 // Match OS specific word break behavior.
846 #if defined(OS_WIN)
847 size_t pos;
848 if (direction == CURSOR_RIGHT) {
849 pos = std::min(selection.caret_pos() + 1, text().length());
850 while (iter.Advance()) {
851 pos = iter.pos();
852 if (iter.IsWord() && pos > selection.caret_pos())
853 break;
855 } else { // direction == CURSOR_LEFT
856 // Notes: We always iterate words from the beginning.
857 // This is probably fast enough for our usage, but we may
858 // want to modify WordIterator so that it can start from the
859 // middle of string and advance backwards.
860 pos = std::max<int>(selection.caret_pos() - 1, 0);
861 while (iter.Advance()) {
862 if (iter.IsWord()) {
863 size_t begin = iter.pos() - iter.GetString().length();
864 if (begin == selection.caret_pos()) {
865 // The cursor is at the beginning of a word.
866 // Move to previous word.
867 break;
868 } else if (iter.pos() >= selection.caret_pos()) {
869 // The cursor is in the middle or at the end of a word.
870 // Move to the top of current word.
871 pos = begin;
872 break;
874 pos = iter.pos() - iter.GetString().length();
878 return SelectionModel(pos, CURSOR_FORWARD);
879 #else
880 internal::TextRunList* run_list = GetRunList();
881 SelectionModel cur(selection);
882 for (;;) {
883 cur = AdjacentCharSelectionModel(cur, direction);
884 size_t run = GetRunContainingCaret(cur);
885 if (run == run_list->size())
886 break;
887 const bool is_forward =
888 run_list->runs()[run]->is_rtl == (direction == CURSOR_LEFT);
889 size_t cursor = cur.caret_pos();
890 if (is_forward ? iter.IsEndOfWord(cursor) : iter.IsStartOfWord(cursor))
891 break;
893 return cur;
894 #endif
897 std::vector<Rect> RenderTextHarfBuzz::GetSubstringBounds(const Range& range) {
898 DCHECK(!update_display_run_list_);
899 DCHECK(Range(0, text().length()).Contains(range));
900 Range layout_range(TextIndexToDisplayIndex(range.start()),
901 TextIndexToDisplayIndex(range.end()));
902 DCHECK(Range(0, GetDisplayText().length()).Contains(layout_range));
904 std::vector<Rect> rects;
905 if (layout_range.is_empty())
906 return rects;
907 std::vector<Range> bounds;
909 internal::TextRunList* run_list = GetRunList();
911 // Add a Range for each run/selection intersection.
912 for (size_t i = 0; i < run_list->size(); ++i) {
913 internal::TextRunHarfBuzz* run =
914 run_list->runs()[run_list->visual_to_logical(i)];
915 Range intersection = run->range.Intersect(layout_range);
916 if (!intersection.IsValid())
917 continue;
918 DCHECK(!intersection.is_reversed());
919 const Range leftmost_character_x = RoundRangeF(run->GetGraphemeBounds(
920 GetGraphemeIterator(),
921 run->is_rtl ? intersection.end() - 1 : intersection.start()));
922 const Range rightmost_character_x = RoundRangeF(run->GetGraphemeBounds(
923 GetGraphemeIterator(),
924 run->is_rtl ? intersection.start() : intersection.end() - 1));
925 Range range_x(leftmost_character_x.start(), rightmost_character_x.end());
926 DCHECK(!range_x.is_reversed());
927 if (range_x.is_empty())
928 continue;
930 // Union this with the last range if they're adjacent.
931 DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin());
932 if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) {
933 range_x = Range(bounds.back().GetMin(), range_x.GetMax());
934 bounds.pop_back();
936 bounds.push_back(range_x);
938 for (Range& bound : bounds) {
939 std::vector<Rect> current_rects = TextBoundsToViewBounds(bound);
940 rects.insert(rects.end(), current_rects.begin(), current_rects.end());
942 return rects;
945 size_t RenderTextHarfBuzz::TextIndexToDisplayIndex(size_t index) {
946 return TextIndexToGivenTextIndex(GetDisplayText(), index);
949 size_t RenderTextHarfBuzz::DisplayIndexToTextIndex(size_t index) {
950 if (!obscured())
951 return index;
952 const size_t text_index = UTF16OffsetToIndex(text(), 0, index);
953 DCHECK_LE(text_index, text().length());
954 return text_index;
957 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index) {
958 if (index == 0 || index == text().length())
959 return true;
960 if (!IsValidLogicalIndex(index))
961 return false;
962 base::i18n::BreakIterator* grapheme_iterator = GetGraphemeIterator();
963 return !grapheme_iterator || grapheme_iterator->IsGraphemeBoundary(index);
966 void RenderTextHarfBuzz::OnLayoutTextAttributeChanged(bool text_changed) {
967 update_layout_run_list_ = true;
968 OnDisplayTextAttributeChanged();
971 void RenderTextHarfBuzz::OnDisplayTextAttributeChanged() {
972 update_display_text_ = true;
973 update_grapheme_iterator_ = true;
976 void RenderTextHarfBuzz::EnsureLayout() {
977 EnsureLayoutRunList();
979 if (update_display_run_list_) {
980 DCHECK(text_elided());
981 const base::string16& display_text = GetDisplayText();
982 display_run_list_.reset(new internal::TextRunList);
984 if (!display_text.empty()) {
985 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayout1");
987 ItemizeTextToRuns(display_text, display_run_list_.get());
989 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
990 // fixed.
991 tracked_objects::ScopedTracker tracking_profile(
992 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 1"));
993 ShapeRunList(display_text, display_run_list_.get());
995 update_display_run_list_ = false;
997 std::vector<internal::Line> empty_lines;
998 set_lines(&empty_lines);
1001 if (lines().empty()) {
1002 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1003 // fixed.
1004 scoped_ptr<tracked_objects::ScopedTracker> tracking_profile(
1005 new tracked_objects::ScopedTracker(
1006 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 HarfBuzzLineBreaker")));
1008 internal::TextRunList* run_list = GetRunList();
1009 HarfBuzzLineBreaker line_breaker(
1010 display_rect().width(), font_list().GetBaseline(),
1011 std::max(font_list().GetHeight(), min_line_height()), multiline(),
1012 word_wrap_behavior(), GetDisplayText(),
1013 multiline() ? &GetLineBreaks() : nullptr, *run_list);
1015 tracking_profile.reset();
1017 for (size_t i = 0; i < run_list->size(); ++i)
1018 line_breaker.AddRun(i);
1019 std::vector<internal::Line> lines;
1020 line_breaker.Finalize(&lines, &total_size_);
1021 set_lines(&lines);
1025 void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) {
1026 internal::SkiaTextRenderer renderer(canvas);
1027 DrawVisualTextInternal(&renderer);
1030 void RenderTextHarfBuzz::DrawVisualTextInternal(
1031 internal::SkiaTextRenderer* renderer) {
1032 DCHECK(!update_layout_run_list_);
1033 DCHECK(!update_display_run_list_);
1034 DCHECK(!update_display_text_);
1035 if (lines().empty())
1036 return;
1038 ApplyFadeEffects(renderer);
1039 ApplyTextShadows(renderer);
1040 ApplyCompositionAndSelectionStyles();
1042 internal::TextRunList* run_list = GetRunList();
1043 for (size_t i = 0; i < lines().size(); ++i) {
1044 const internal::Line& line = lines()[i];
1045 const Vector2d origin = GetLineOffset(i) + Vector2d(0, line.baseline);
1046 SkScalar preceding_segment_widths = 0;
1047 for (const internal::LineSegment& segment : line.segments) {
1048 const internal::TextRunHarfBuzz& run = *run_list->runs()[segment.run];
1049 renderer->SetTypeface(run.skia_face.get());
1050 renderer->SetTextSize(SkIntToScalar(run.font_size));
1051 renderer->SetFontRenderParams(run.render_params,
1052 subpixel_rendering_suppressed());
1053 Range glyphs_range = run.CharRangeToGlyphRange(segment.char_range);
1054 scoped_ptr<SkPoint[]> positions(new SkPoint[glyphs_range.length()]);
1055 SkScalar offset_x = preceding_segment_widths -
1056 ((glyphs_range.GetMin() != 0)
1057 ? run.positions[glyphs_range.GetMin()].x()
1058 : 0);
1059 for (size_t j = 0; j < glyphs_range.length(); ++j) {
1060 positions[j] = run.positions[(glyphs_range.is_reversed()) ?
1061 (glyphs_range.start() - j) :
1062 (glyphs_range.start() + j)];
1063 positions[j].offset(SkIntToScalar(origin.x()) + offset_x,
1064 SkIntToScalar(origin.y() + run.baseline_offset));
1066 for (BreakList<SkColor>::const_iterator it =
1067 colors().GetBreak(segment.char_range.start());
1068 it != colors().breaks().end() &&
1069 it->first < segment.char_range.end();
1070 ++it) {
1071 const Range intersection =
1072 colors().GetRange(it).Intersect(segment.char_range);
1073 const Range colored_glyphs = run.CharRangeToGlyphRange(intersection);
1074 // The range may be empty if a portion of a multi-character grapheme is
1075 // selected, yielding two colors for a single glyph. For now, this just
1076 // paints the glyph with a single style, but it should paint it twice,
1077 // clipped according to selection bounds. See http://crbug.com/366786
1078 if (colored_glyphs.is_empty())
1079 continue;
1081 renderer->SetForegroundColor(it->second);
1082 renderer->DrawPosText(
1083 &positions[colored_glyphs.start() - glyphs_range.start()],
1084 &run.glyphs[colored_glyphs.start()], colored_glyphs.length());
1085 int start_x = SkScalarRoundToInt(
1086 positions[colored_glyphs.start() - glyphs_range.start()].x());
1087 int end_x = SkScalarRoundToInt(
1088 (colored_glyphs.end() == glyphs_range.end())
1089 ? (SkFloatToScalar(segment.width) + preceding_segment_widths +
1090 SkIntToScalar(origin.x()))
1091 : positions[colored_glyphs.end() - glyphs_range.start()].x());
1092 renderer->DrawDecorations(start_x, origin.y(), end_x - start_x,
1093 run.underline, run.strike,
1094 run.diagonal_strike);
1096 preceding_segment_widths += SkFloatToScalar(segment.width);
1100 renderer->EndDiagonalStrike();
1102 UndoCompositionAndSelectionStyles();
1105 size_t RenderTextHarfBuzz::GetRunContainingCaret(
1106 const SelectionModel& caret) {
1107 DCHECK(!update_display_run_list_);
1108 size_t layout_position = TextIndexToDisplayIndex(caret.caret_pos());
1109 LogicalCursorDirection affinity = caret.caret_affinity();
1110 internal::TextRunList* run_list = GetRunList();
1111 for (size_t i = 0; i < run_list->size(); ++i) {
1112 internal::TextRunHarfBuzz* run = run_list->runs()[i];
1113 if (RangeContainsCaret(run->range, layout_position, affinity))
1114 return i;
1116 return run_list->size();
1119 size_t RenderTextHarfBuzz::GetRunContainingXCoord(float x,
1120 float* offset) const {
1121 DCHECK(!update_display_run_list_);
1122 const internal::TextRunList* run_list = GetRunList();
1123 if (x < 0)
1124 return run_list->size();
1125 // Find the text run containing the argument point (assumed already offset).
1126 float current_x = 0;
1127 for (size_t i = 0; i < run_list->size(); ++i) {
1128 size_t run = run_list->visual_to_logical(i);
1129 current_x += run_list->runs()[run]->width;
1130 if (x < current_x) {
1131 *offset = x - (current_x - run_list->runs()[run]->width);
1132 return run;
1135 return run_list->size();
1138 SelectionModel RenderTextHarfBuzz::FirstSelectionModelInsideRun(
1139 const internal::TextRunHarfBuzz* run) {
1140 size_t position = DisplayIndexToTextIndex(run->range.start());
1141 position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD);
1142 return SelectionModel(position, CURSOR_BACKWARD);
1145 SelectionModel RenderTextHarfBuzz::LastSelectionModelInsideRun(
1146 const internal::TextRunHarfBuzz* run) {
1147 size_t position = DisplayIndexToTextIndex(run->range.end());
1148 position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD);
1149 return SelectionModel(position, CURSOR_FORWARD);
1152 void RenderTextHarfBuzz::ItemizeTextToRuns(
1153 const base::string16& text,
1154 internal::TextRunList* run_list_out) {
1155 const bool is_text_rtl = GetTextDirection(text) == base::i18n::RIGHT_TO_LEFT;
1156 DCHECK_NE(0U, text.length());
1158 // If ICU fails to itemize the text, we create a run that spans the entire
1159 // text. This is needed because leaving the runs set empty causes some clients
1160 // to misbehave since they expect non-zero text metrics from a non-empty text.
1161 base::i18n::BiDiLineIterator bidi_iterator;
1162 if (!bidi_iterator.Open(text, is_text_rtl, false)) {
1163 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
1164 run->range = Range(0, text.length());
1165 run_list_out->add(run);
1166 run_list_out->InitIndexMap();
1167 return;
1170 // Temporarily apply composition underlines and selection colors.
1171 ApplyCompositionAndSelectionStyles();
1173 // Build the run list from the script items and ranged styles and baselines.
1174 // Use an empty color BreakList to avoid breaking runs at color boundaries.
1175 BreakList<SkColor> empty_colors;
1176 empty_colors.SetMax(text.length());
1177 DCHECK_LE(text.size(), baselines().max());
1178 for (const BreakList<bool>& style : styles())
1179 DCHECK_LE(text.size(), style.max());
1180 internal::StyleIterator style(empty_colors, baselines(), styles());
1182 for (size_t run_break = 0; run_break < text.length();) {
1183 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
1184 run->range.set_start(run_break);
1185 run->font_style = (style.style(BOLD) ? Font::BOLD : 0) |
1186 (style.style(ITALIC) ? Font::ITALIC : 0);
1187 run->baseline_type = style.baseline();
1188 run->strike = style.style(STRIKE);
1189 run->diagonal_strike = style.style(DIAGONAL_STRIKE);
1190 run->underline = style.style(UNDERLINE);
1191 int32 script_item_break = 0;
1192 bidi_iterator.GetLogicalRun(run_break, &script_item_break, &run->level);
1193 // Odd BiDi embedding levels correspond to RTL runs.
1194 run->is_rtl = (run->level % 2) == 1;
1195 // Find the length and script of this script run.
1196 script_item_break = ScriptInterval(text, run_break,
1197 script_item_break - run_break, &run->script) + run_break;
1199 // Find the next break and advance the iterators as needed.
1200 run_break = std::min(
1201 static_cast<size_t>(script_item_break),
1202 TextIndexToGivenTextIndex(text, style.GetRange().end()));
1204 // Break runs at certain characters that need to be rendered separately to
1205 // prevent either an unusual character from forcing a fallback font on the
1206 // entire run, or brackets from being affected by a fallback font.
1207 // http://crbug.com/278913, http://crbug.com/396776
1208 if (run_break > run->range.start())
1209 run_break = FindRunBreakingCharacter(text, run->range.start(), run_break);
1211 DCHECK(IsValidCodePointIndex(text, run_break));
1212 style.UpdatePosition(DisplayIndexToTextIndex(run_break));
1213 run->range.set_end(run_break);
1215 run_list_out->add(run);
1218 // Undo the temporarily applied composition underlines and selection colors.
1219 UndoCompositionAndSelectionStyles();
1221 run_list_out->InitIndexMap();
1224 bool RenderTextHarfBuzz::CompareFamily(
1225 const base::string16& text,
1226 const std::string& family,
1227 const gfx::FontRenderParams& render_params,
1228 internal::TextRunHarfBuzz* run,
1229 std::string* best_family,
1230 gfx::FontRenderParams* best_render_params,
1231 size_t* best_missing_glyphs) {
1232 if (!ShapeRunWithFont(text, family, render_params, run))
1233 return false;
1235 const size_t missing_glyphs = run->CountMissingGlyphs();
1236 if (missing_glyphs < *best_missing_glyphs) {
1237 *best_family = family;
1238 *best_render_params = render_params;
1239 *best_missing_glyphs = missing_glyphs;
1241 return missing_glyphs == 0;
1244 void RenderTextHarfBuzz::ShapeRunList(const base::string16& text,
1245 internal::TextRunList* run_list) {
1246 for (auto* run : run_list->runs())
1247 ShapeRun(text, run);
1248 run_list->ComputePrecedingRunWidths();
1251 void RenderTextHarfBuzz::ShapeRun(const base::string16& text,
1252 internal::TextRunHarfBuzz* run) {
1253 const Font& primary_font = font_list().GetPrimaryFont();
1254 const std::string primary_family = primary_font.GetFontName();
1255 run->font_size = primary_font.GetFontSize();
1256 run->baseline_offset = 0;
1257 if (run->baseline_type != NORMAL_BASELINE) {
1258 // Calculate a slightly smaller font. The ratio here is somewhat arbitrary.
1259 // Proportions from 5/9 to 5/7 all look pretty good.
1260 const float ratio = 5.0f / 9.0f;
1261 run->font_size = gfx::ToRoundedInt(primary_font.GetFontSize() * ratio);
1262 switch (run->baseline_type) {
1263 case SUPERSCRIPT:
1264 run->baseline_offset =
1265 primary_font.GetCapHeight() - primary_font.GetHeight();
1266 break;
1267 case SUPERIOR:
1268 run->baseline_offset =
1269 gfx::ToRoundedInt(primary_font.GetCapHeight() * ratio) -
1270 primary_font.GetCapHeight();
1271 break;
1272 case SUBSCRIPT:
1273 run->baseline_offset =
1274 primary_font.GetHeight() - primary_font.GetBaseline();
1275 break;
1276 case INFERIOR: // Fall through.
1277 default:
1278 break;
1282 std::string best_family;
1283 FontRenderParams best_render_params;
1284 size_t best_missing_glyphs = std::numeric_limits<size_t>::max();
1286 for (const Font& font : font_list().GetFonts()) {
1287 if (CompareFamily(text, font.GetFontName(), font.GetFontRenderParams(),
1288 run, &best_family, &best_render_params,
1289 &best_missing_glyphs))
1290 return;
1293 #if defined(OS_WIN)
1294 Font uniscribe_font;
1295 std::string uniscribe_family;
1296 const base::char16* run_text = &(text[run->range.start()]);
1297 if (GetUniscribeFallbackFont(primary_font, run_text, run->range.length(),
1298 &uniscribe_font)) {
1299 uniscribe_family = uniscribe_font.GetFontName();
1300 if (CompareFamily(text, uniscribe_family,
1301 uniscribe_font.GetFontRenderParams(), run,
1302 &best_family, &best_render_params, &best_missing_glyphs))
1303 return;
1305 #endif
1307 std::vector<std::string> fallback_families =
1308 GetFallbackFontFamilies(primary_family);
1310 #if defined(OS_WIN)
1311 // Append fonts in the fallback list of the Uniscribe font.
1312 if (!uniscribe_family.empty()) {
1313 std::vector<std::string> uniscribe_fallbacks =
1314 GetFallbackFontFamilies(uniscribe_family);
1315 fallback_families.insert(fallback_families.end(),
1316 uniscribe_fallbacks.begin(), uniscribe_fallbacks.end());
1319 // Add Segoe UI and its associated linked fonts to the fallback font list to
1320 // ensure that the fallback list covers the basic cases.
1321 // http://crbug.com/467459. On some Windows configurations the default font
1322 // could be a raster font like System, which would not give us a reasonable
1323 // fallback font list.
1324 if (!LowerCaseEqualsASCII(primary_family, "segoe ui") &&
1325 !LowerCaseEqualsASCII(uniscribe_family, "segoe ui")) {
1326 std::vector<std::string> default_fallback_families =
1327 GetFallbackFontFamilies("Segoe UI");
1328 fallback_families.insert(fallback_families.end(),
1329 default_fallback_families.begin(), default_fallback_families.end());
1331 #endif
1333 // Use a set to track the fallback fonts and avoid duplicate entries.
1334 std::set<std::string, CaseInsensitiveCompare> fallback_fonts;
1336 // Try shaping with the fallback fonts.
1337 for (const auto& family : fallback_families) {
1338 if (family == primary_family)
1339 continue;
1340 #if defined(OS_WIN)
1341 if (family == uniscribe_family)
1342 continue;
1343 #endif
1344 if (fallback_fonts.find(family) != fallback_fonts.end())
1345 continue;
1347 fallback_fonts.insert(family);
1349 FontRenderParamsQuery query;
1350 query.families.push_back(family);
1351 query.pixel_size = run->font_size;
1352 query.style = run->font_style;
1353 FontRenderParams fallback_render_params = GetFontRenderParams(query, NULL);
1354 if (CompareFamily(text, family, fallback_render_params, run, &best_family,
1355 &best_render_params, &best_missing_glyphs))
1356 return;
1359 if (!best_family.empty() &&
1360 (best_family == run->family ||
1361 ShapeRunWithFont(text, best_family, best_render_params, run)))
1362 return;
1364 run->glyph_count = 0;
1365 run->width = 0.0f;
1368 bool RenderTextHarfBuzz::ShapeRunWithFont(const base::string16& text,
1369 const std::string& font_family,
1370 const FontRenderParams& params,
1371 internal::TextRunHarfBuzz* run) {
1372 skia::RefPtr<SkTypeface> skia_face =
1373 internal::CreateSkiaTypeface(font_family, run->font_style);
1374 if (skia_face == NULL)
1375 return false;
1376 run->skia_face = skia_face;
1377 run->family = font_family;
1378 run->render_params = params;
1380 hb_font_t* harfbuzz_font = CreateHarfBuzzFont(
1381 run->skia_face.get(), SkIntToScalar(run->font_size), run->render_params,
1382 subpixel_rendering_suppressed());
1384 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
1385 // buffer holds our text, run information to be used by the shaping engine,
1386 // and the resulting glyph data.
1387 hb_buffer_t* buffer = hb_buffer_create();
1388 hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16*>(text.c_str()),
1389 text.length(), run->range.start(), run->range.length());
1390 hb_buffer_set_script(buffer, ICUScriptToHBScript(run->script));
1391 hb_buffer_set_direction(buffer,
1392 run->is_rtl ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
1393 // TODO(ckocagil): Should we determine the actual language?
1394 hb_buffer_set_language(buffer, hb_language_get_default());
1397 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1398 // fixed.
1399 tracked_objects::ScopedTracker tracking_profile(
1400 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 hb_shape()"));
1402 // Shape the text.
1403 hb_shape(harfbuzz_font, buffer, NULL, 0);
1406 // Populate the run fields with the resulting glyph data in the buffer.
1407 unsigned int glyph_count = 0;
1408 hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(buffer, &glyph_count);
1409 run->glyph_count = glyph_count;
1410 hb_glyph_position_t* hb_positions =
1411 hb_buffer_get_glyph_positions(buffer, NULL);
1412 run->glyphs.reset(new uint16[run->glyph_count]);
1413 run->glyph_to_char.resize(run->glyph_count);
1414 run->positions.reset(new SkPoint[run->glyph_count]);
1415 run->width = 0.0f;
1417 for (size_t i = 0; i < run->glyph_count; ++i) {
1418 DCHECK_LE(infos[i].codepoint, std::numeric_limits<uint16>::max());
1419 run->glyphs[i] = static_cast<uint16>(infos[i].codepoint);
1420 run->glyph_to_char[i] = infos[i].cluster;
1421 const SkScalar x_offset = SkFixedToScalar(hb_positions[i].x_offset);
1422 const SkScalar y_offset = SkFixedToScalar(hb_positions[i].y_offset);
1423 run->positions[i].set(run->width + x_offset, -y_offset);
1424 run->width += (glyph_width_for_test_ > 0)
1425 ? glyph_width_for_test_
1426 : SkFixedToFloat(hb_positions[i].x_advance);
1427 // Round run widths if subpixel positioning is off to match native behavior.
1428 if (!run->render_params.subpixel_positioning)
1429 run->width = std::floor(run->width + 0.5f);
1432 hb_buffer_destroy(buffer);
1433 hb_font_destroy(harfbuzz_font);
1434 return true;
1437 void RenderTextHarfBuzz::EnsureLayoutRunList() {
1438 if (update_layout_run_list_) {
1439 layout_run_list_.Reset();
1441 const base::string16& text = layout_text();
1442 if (!text.empty()) {
1443 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayoutRunList");
1444 ItemizeTextToRuns(text, &layout_run_list_);
1446 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1447 // fixed.
1448 tracked_objects::ScopedTracker tracking_profile(
1449 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 2"));
1450 ShapeRunList(text, &layout_run_list_);
1453 std::vector<internal::Line> empty_lines;
1454 set_lines(&empty_lines);
1455 display_run_list_.reset();
1456 update_display_text_ = true;
1457 update_layout_run_list_ = false;
1459 if (update_display_text_) {
1460 UpdateDisplayText(multiline() ? 0 : layout_run_list_.width());
1461 update_display_text_ = false;
1462 update_display_run_list_ = text_elided();
1466 base::i18n::BreakIterator* RenderTextHarfBuzz::GetGraphemeIterator() {
1467 if (update_grapheme_iterator_) {
1468 update_grapheme_iterator_ = false;
1469 grapheme_iterator_.reset(new base::i18n::BreakIterator(
1470 GetDisplayText(),
1471 base::i18n::BreakIterator::BREAK_CHARACTER));
1472 if (!grapheme_iterator_->Init())
1473 grapheme_iterator_.reset();
1475 return grapheme_iterator_.get();
1478 internal::TextRunList* RenderTextHarfBuzz::GetRunList() {
1479 DCHECK(!update_layout_run_list_);
1480 DCHECK(!update_display_run_list_);
1481 return text_elided() ? display_run_list_.get() : &layout_run_list_;
1484 const internal::TextRunList* RenderTextHarfBuzz::GetRunList() const {
1485 return const_cast<RenderTextHarfBuzz*>(this)->GetRunList();
1488 } // namespace gfx