[Android WebView] Put AndroidStreamReaderURLRequestJob into a namespace
[chromium-blink-merge.git] / ui / gfx / render_text_harfbuzz.cc
bloba10e6df03be358e63628d474991d81af4ddfd547
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/icu/source/common/unicode/utf16.h"
20 #include "third_party/skia/include/core/SkColor.h"
21 #include "third_party/skia/include/core/SkTypeface.h"
22 #include "ui/gfx/canvas.h"
23 #include "ui/gfx/font_fallback.h"
24 #include "ui/gfx/font_render_params.h"
25 #include "ui/gfx/geometry/safe_integer_conversions.h"
26 #include "ui/gfx/harfbuzz_font_skia.h"
27 #include "ui/gfx/range/range_f.h"
28 #include "ui/gfx/text_utils.h"
29 #include "ui/gfx/utf16_indexing.h"
31 #if defined(OS_WIN)
32 #include "ui/gfx/font_fallback_win.h"
33 #endif
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;
55 bool IsBracket(UChar32 character) {
56 static const char kBrackets[] = { '(', ')', '{', '}', '<', '>', };
57 static const char* kBracketsEnd = kBrackets + arraysize(kBrackets);
58 return std::find(kBrackets, kBracketsEnd, character) != kBracketsEnd;
61 // Returns the boundary between a special and a regular character. Special
62 // characters are brackets or characters that satisfy |IsUnusualBlockCode|.
63 size_t FindRunBreakingCharacter(const base::string16& text,
64 size_t run_start,
65 size_t run_break) {
66 const int32 run_length = static_cast<int32>(run_break - run_start);
67 base::i18n::UTF16CharIterator iter(text.c_str() + run_start, run_length);
68 const UChar32 first_char = iter.get();
69 // The newline character should form a single run so that the line breaker
70 // can handle them easily.
71 if (first_char == '\n')
72 return run_start + 1;
74 const UBlockCode first_block = ublock_getCode(first_char);
75 const bool first_block_unusual = IsUnusualBlockCode(first_block);
76 const bool first_bracket = IsBracket(first_char);
78 while (iter.Advance() && iter.array_pos() < run_length) {
79 const UChar32 current_char = iter.get();
80 const UBlockCode current_block = ublock_getCode(current_char);
81 const bool block_break = current_block != first_block &&
82 (first_block_unusual || IsUnusualBlockCode(current_block));
83 if (block_break || current_char == '\n' ||
84 first_bracket != IsBracket(current_char)) {
85 return run_start + iter.array_pos();
88 return run_break;
91 // If the given scripts match, returns the one that isn't USCRIPT_INHERITED,
92 // i.e. the more specific one. Otherwise returns USCRIPT_INVALID_CODE.
93 UScriptCode ScriptIntersect(UScriptCode first, UScriptCode second) {
94 if (first == second || second == USCRIPT_INHERITED)
95 return first;
96 if (first == USCRIPT_INHERITED)
97 return second;
98 return USCRIPT_INVALID_CODE;
101 // Writes the script and the script extensions of the character with the
102 // Unicode |codepoint|. Returns the number of written scripts.
103 int GetScriptExtensions(UChar32 codepoint, UScriptCode* scripts) {
104 UErrorCode icu_error = U_ZERO_ERROR;
105 // ICU documentation incorrectly states that the result of
106 // |uscript_getScriptExtensions| will contain the regular script property.
107 // Write the character's script property to the first element.
108 scripts[0] = uscript_getScript(codepoint, &icu_error);
109 if (U_FAILURE(icu_error))
110 return 0;
111 // Fill the rest of |scripts| with the extensions.
112 int count = uscript_getScriptExtensions(codepoint, scripts + 1,
113 kMaxScripts - 1, &icu_error);
114 if (U_FAILURE(icu_error))
115 count = 0;
116 return count + 1;
119 // Intersects the script extensions set of |codepoint| with |result| and writes
120 // to |result|, reading and updating |result_size|.
121 void ScriptSetIntersect(UChar32 codepoint,
122 UScriptCode* result,
123 size_t* result_size) {
124 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
125 int count = GetScriptExtensions(codepoint, scripts);
127 size_t out_size = 0;
129 for (size_t i = 0; i < *result_size; ++i) {
130 for (int j = 0; j < count; ++j) {
131 UScriptCode intersection = ScriptIntersect(result[i], scripts[j]);
132 if (intersection != USCRIPT_INVALID_CODE) {
133 result[out_size++] = intersection;
134 break;
139 *result_size = out_size;
142 // Find the longest sequence of characters from 0 and up to |length| that
143 // have at least one common UScriptCode value. Writes the common script value to
144 // |script| and returns the length of the sequence. Takes the characters' script
145 // extensions into account. http://www.unicode.org/reports/tr24/#ScriptX
147 // Consider 3 characters with the script values {Kana}, {Hira, Kana}, {Kana}.
148 // Without script extensions only the first script in each set would be taken
149 // into account, resulting in 3 runs where 1 would be enough.
150 // TODO(ckocagil): Write a unit test for the case above.
151 int ScriptInterval(const base::string16& text,
152 size_t start,
153 size_t length,
154 UScriptCode* script) {
155 DCHECK_GT(length, 0U);
157 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
159 base::i18n::UTF16CharIterator char_iterator(text.c_str() + start, length);
160 size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts);
161 *script = scripts[0];
163 while (char_iterator.Advance()) {
164 // Special handling to merge white space into the previous run.
165 if (u_isUWhiteSpace(char_iterator.get()))
166 continue;
167 ScriptSetIntersect(char_iterator.get(), scripts, &scripts_size);
168 if (scripts_size == 0U)
169 return char_iterator.array_pos();
170 *script = scripts[0];
173 return length;
176 // A port of hb_icu_script_to_script because harfbuzz on CrOS is built without
177 // hb-icu. See http://crbug.com/356929
178 inline hb_script_t ICUScriptToHBScript(UScriptCode script) {
179 if (script == USCRIPT_INVALID_CODE)
180 return HB_SCRIPT_INVALID;
181 return hb_script_from_string(uscript_getShortName(script), -1);
184 // Helper template function for |TextRunHarfBuzz::GetClusterAt()|. |Iterator|
185 // can be a forward or reverse iterator type depending on the text direction.
186 template <class Iterator>
187 void GetClusterAtImpl(size_t pos,
188 Range range,
189 Iterator elements_begin,
190 Iterator elements_end,
191 bool reversed,
192 Range* chars,
193 Range* glyphs) {
194 Iterator element = std::upper_bound(elements_begin, elements_end, pos);
195 chars->set_end(element == elements_end ? range.end() : *element);
196 glyphs->set_end(reversed ? elements_end - element : element - elements_begin);
198 DCHECK(element != elements_begin);
199 while (--element != elements_begin && *element == *(element - 1));
200 chars->set_start(*element);
201 glyphs->set_start(
202 reversed ? elements_end - element : element - elements_begin);
203 if (reversed)
204 *glyphs = Range(glyphs->end(), glyphs->start());
206 DCHECK(!chars->is_reversed());
207 DCHECK(!chars->is_empty());
208 DCHECK(!glyphs->is_reversed());
209 DCHECK(!glyphs->is_empty());
212 // Internal class to generate Line structures. If |multiline| is true, the text
213 // is broken into lines at |words| boundaries such that each line is no longer
214 // than |max_width|. If |multiline| is false, only outputs a single Line from
215 // the given runs. |min_baseline| and |min_height| are the minimum baseline and
216 // height for each line.
217 // TODO(ckocagil): Expose the interface of this class in the header and test
218 // this class directly.
219 class HarfBuzzLineBreaker {
220 public:
221 HarfBuzzLineBreaker(size_t max_width,
222 int min_baseline,
223 float min_height,
224 WordWrapBehavior word_wrap_behavior,
225 const base::string16& text,
226 const BreakList<size_t>* words,
227 const internal::TextRunList& run_list)
228 : max_width_((max_width == 0) ? SK_ScalarMax : SkIntToScalar(max_width)),
229 min_baseline_(min_baseline),
230 min_height_(min_height),
231 word_wrap_behavior_(word_wrap_behavior),
232 text_(text),
233 words_(words),
234 run_list_(run_list),
235 max_descent_(0),
236 max_ascent_(0),
237 text_x_(0),
238 available_width_(max_width_) {
239 AdvanceLine();
242 // Constructs a single line for |text_| using |run_list_|.
243 void ConstructSingleLine() {
244 for (size_t i = 0; i < run_list_.size(); i++) {
245 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[i]);
246 internal::LineSegment segment;
247 segment.run = i;
248 segment.char_range = run.range;
249 segment.x_range = RangeF(SkScalarToFloat(text_x_),
250 SkScalarToFloat(text_x_) + run.width);
251 AddLineSegment(segment);
255 // Constructs multiple lines for |text_| based on words iteration approach.
256 void ConstructMultiLines() {
257 DCHECK(words_);
258 for (auto iter = words_->breaks().begin(); iter != words_->breaks().end();
259 iter++) {
260 const Range word_range = words_->GetRange(iter);
261 std::vector<internal::LineSegment> word_segments;
262 SkScalar word_width = GetWordWidth(word_range, &word_segments);
264 // If the last word is '\n', we should advance a new line after adding
265 // the word to the current line.
266 bool new_line = false;
267 if (!word_segments.empty() &&
268 text_[word_segments.back().char_range.start()] == '\n') {
269 new_line = true;
270 word_width -= word_segments.back().width();
271 word_segments.pop_back();
274 // If the word is not the first word in the line and it can't fit into
275 // the current line, advance a new line.
276 if (word_width > available_width_ && available_width_ != max_width_)
277 AdvanceLine();
278 if (!word_segments.empty())
279 AddWordToLine(word_segments);
280 if (new_line)
281 AdvanceLine();
285 // Finishes line breaking and outputs the results. Can be called at most once.
286 void FinalizeLines(std::vector<internal::Line>* lines, SizeF* size) {
287 DCHECK(!lines_.empty());
288 // Add an empty line to finish the line size calculation and remove it.
289 AdvanceLine();
290 lines_.pop_back();
291 *size = total_size_;
292 lines->swap(lines_);
295 private:
296 // A (line index, segment index) pair that specifies a segment in |lines_|.
297 typedef std::pair<size_t, size_t> SegmentHandle;
299 internal::LineSegment* SegmentFromHandle(const SegmentHandle& handle) {
300 return &lines_[handle.first].segments[handle.second];
303 // Finishes the size calculations of the last Line in |lines_|. Adds a new
304 // Line to the back of |lines_|.
305 void AdvanceLine() {
306 if (!lines_.empty()) {
307 internal::Line* line = &lines_.back();
308 std::sort(line->segments.begin(), line->segments.end(),
309 [this](const internal::LineSegment& s1,
310 const internal::LineSegment& s2) -> bool {
311 return run_list_.logical_to_visual(s1.run) <
312 run_list_.logical_to_visual(s2.run);
314 line->size.set_height(std::max(min_height_, max_descent_ + max_ascent_));
315 line->baseline = std::max(min_baseline_, SkScalarRoundToInt(max_ascent_));
316 line->preceding_heights = std::ceil(total_size_.height());
317 total_size_.set_height(total_size_.height() + line->size.height());
318 total_size_.set_width(std::max(total_size_.width(), line->size.width()));
320 max_descent_ = 0;
321 max_ascent_ = 0;
322 available_width_ = max_width_;
323 lines_.push_back(internal::Line());
326 // Adds word to the current line. A word may contain multiple segments. If the
327 // word is the first word in line and its width exceeds |available_width_|,
328 // ignore/truncate/wrap it according to |word_wrap_behavior_|.
329 void AddWordToLine(const std::vector<internal::LineSegment>& word_segments) {
330 DCHECK(!lines_.empty());
331 DCHECK(!word_segments.empty());
333 bool has_truncated = false;
334 for (const internal::LineSegment& segment : word_segments) {
335 if (has_truncated)
336 break;
337 if (segment.width() <= available_width_ ||
338 word_wrap_behavior_ == IGNORE_LONG_WORDS) {
339 AddLineSegment(segment);
340 } else {
341 DCHECK(word_wrap_behavior_ == TRUNCATE_LONG_WORDS ||
342 word_wrap_behavior_ == WRAP_LONG_WORDS);
343 has_truncated = (word_wrap_behavior_ == TRUNCATE_LONG_WORDS);
345 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[segment.run]);
346 internal::LineSegment remaining_segment = segment;
347 while (!remaining_segment.char_range.is_empty()) {
348 size_t cutoff_pos = GetCutoffPos(remaining_segment);
349 SkScalar width = run.GetGlyphWidthForCharRange(
350 Range(remaining_segment.char_range.start(), cutoff_pos));
351 if (width > 0) {
352 internal::LineSegment cut_segment;
353 cut_segment.run = remaining_segment.run;
354 cut_segment.char_range =
355 Range(remaining_segment.char_range.start(), cutoff_pos);
356 cut_segment.x_range = RangeF(SkScalarToFloat(text_x_),
357 SkScalarToFloat(text_x_ + width));
358 AddLineSegment(cut_segment);
359 // Updates old segment range.
360 remaining_segment.char_range.set_start(cutoff_pos);
361 remaining_segment.x_range.set_start(SkScalarToFloat(text_x_));
363 if (has_truncated)
364 break;
365 if (!remaining_segment.char_range.is_empty())
366 AdvanceLine();
372 // Add a line segment to the current line. Note that, in order to keep the
373 // visual order correct for ltr and rtl language, we need to merge segments
374 // that belong to the same run.
375 void AddLineSegment(const internal::LineSegment& segment) {
376 DCHECK(!lines_.empty());
377 internal::Line* line = &lines_.back();
378 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[segment.run]);
379 if (!line->segments.empty()) {
380 internal::LineSegment& last_segment = line->segments.back();
381 // Merge segments that belong to the same run.
382 if (last_segment.run == segment.run) {
383 DCHECK_EQ(last_segment.char_range.end(), segment.char_range.start());
384 DCHECK_LE(
385 std::abs(last_segment.x_range.end() - segment.x_range.start()),
386 std::numeric_limits<float>::epsilon());
387 last_segment.char_range.set_end(segment.char_range.end());
388 last_segment.x_range.set_end(SkScalarToFloat(text_x_) +
389 segment.width());
390 if (run.is_rtl && last_segment.char_range.end() == run.range.end())
391 UpdateRTLSegmentRanges();
392 line->size.set_width(line->size.width() + segment.width());
393 text_x_ += segment.width();
394 available_width_ -= segment.width();
395 return;
398 line->segments.push_back(segment);
400 SkPaint paint;
401 paint.setTypeface(run.skia_face.get());
402 paint.setTextSize(SkIntToScalar(run.font_size));
403 paint.setAntiAlias(run.render_params.antialiasing);
404 SkPaint::FontMetrics metrics;
405 paint.getFontMetrics(&metrics);
407 line->size.set_width(line->size.width() + segment.width());
408 // TODO(dschuyler): Account for stylized baselines in string sizing.
409 max_descent_ = std::max(max_descent_, metrics.fDescent);
410 // fAscent is always negative.
411 max_ascent_ = std::max(max_ascent_, -metrics.fAscent);
413 if (run.is_rtl) {
414 rtl_segments_.push_back(
415 SegmentHandle(lines_.size() - 1, line->segments.size() - 1));
416 // If this is the last segment of an RTL run, reprocess the text-space x
417 // ranges of all segments from the run.
418 if (segment.char_range.end() == run.range.end())
419 UpdateRTLSegmentRanges();
421 text_x_ += segment.width();
422 available_width_ -= segment.width();
425 // Finds the end position |end_pos| in |segment| where the preceding width is
426 // no larger than |available_width_|.
427 size_t GetCutoffPos(const internal::LineSegment& segment) const {
428 DCHECK(!segment.char_range.is_empty());
429 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[segment.run]);
430 size_t end_pos = segment.char_range.start();
431 SkScalar width = 0;
432 while (end_pos < segment.char_range.end()) {
433 const SkScalar char_width =
434 run.GetGlyphWidthForCharRange(Range(end_pos, end_pos + 1));
435 if (width + char_width > available_width_)
436 break;
437 width += char_width;
438 end_pos++;
441 const size_t valid_end_pos = std::max(
442 segment.char_range.start(), FindValidBoundaryBefore(text_, end_pos));
443 if (end_pos != valid_end_pos) {
444 end_pos = valid_end_pos;
445 width = run.GetGlyphWidthForCharRange(
446 Range(segment.char_range.start(), end_pos));
449 // |max_width_| might be smaller than a single character. In this case we
450 // need to put at least one character in the line. Note that, we should
451 // not separate surrogate pair or combining characters.
452 // See RenderTextTest.Multiline_MinWidth for an example.
453 if (width == 0 && available_width_ == max_width_) {
454 end_pos = std::min(segment.char_range.end(),
455 FindValidBoundaryAfter(text_, end_pos + 1));
458 return end_pos;
461 // Gets the glyph width for |word_range|, and splits the |word| into different
462 // segments based on its runs.
463 SkScalar GetWordWidth(const Range& word_range,
464 std::vector<internal::LineSegment>* segments) const {
465 DCHECK(words_);
466 if (word_range.is_empty() || segments == nullptr)
467 return 0;
468 size_t run_start_index = run_list_.GetRunIndexAt(word_range.start());
469 size_t run_end_index = run_list_.GetRunIndexAt(word_range.end() - 1);
470 SkScalar width = 0;
471 for (size_t i = run_start_index; i <= run_end_index; i++) {
472 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[i]);
473 const Range char_range = run.range.Intersect(word_range);
474 DCHECK(!char_range.is_empty());
475 const SkScalar char_width = run.GetGlyphWidthForCharRange(char_range);
476 width += char_width;
478 internal::LineSegment segment;
479 segment.run = i;
480 segment.char_range = char_range;
481 segment.x_range = RangeF(SkScalarToFloat(text_x_ + width - char_width),
482 SkScalarToFloat(text_x_ + width));
483 segments->push_back(segment);
485 return width;
488 // RTL runs are broken in logical order but displayed in visual order. To find
489 // the text-space coordinate (where it would fall in a single-line text)
490 // |x_range| of RTL segments, segment widths are applied in reverse order.
491 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}.
492 void UpdateRTLSegmentRanges() {
493 if (rtl_segments_.empty())
494 return;
495 float x = SegmentFromHandle(rtl_segments_[0])->x_range.start();
496 for (size_t i = rtl_segments_.size(); i > 0; --i) {
497 internal::LineSegment* segment = SegmentFromHandle(rtl_segments_[i - 1]);
498 const float segment_width = segment->width();
499 segment->x_range = RangeF(x, x + segment_width);
500 x += segment_width;
502 rtl_segments_.clear();
505 const SkScalar max_width_;
506 const int min_baseline_;
507 const float min_height_;
508 const WordWrapBehavior word_wrap_behavior_;
509 const base::string16& text_;
510 const BreakList<size_t>* const words_;
511 const internal::TextRunList& run_list_;
513 // Stores the resulting lines.
514 std::vector<internal::Line> lines_;
516 float max_descent_;
517 float max_ascent_;
519 // Text space x coordinates of the next segment to be added.
520 SkScalar text_x_;
521 // Stores available width in the current line.
522 SkScalar available_width_;
524 // Size of the multiline text, not including the currently processed line.
525 SizeF total_size_;
527 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
528 std::vector<SegmentHandle> rtl_segments_;
530 DISALLOW_COPY_AND_ASSIGN(HarfBuzzLineBreaker);
533 // Function object for case insensitive string comparison.
534 struct CaseInsensitiveCompare {
535 bool operator() (const std::string& a, const std::string& b) const {
536 return base::CompareCaseInsensitiveASCII(a, b) < 0;
540 } // namespace
542 namespace internal {
544 TextRunHarfBuzz::TextRunHarfBuzz()
545 : width(0.0f),
546 preceding_run_widths(0.0f),
547 is_rtl(false),
548 level(0),
549 script(USCRIPT_INVALID_CODE),
550 glyph_count(static_cast<size_t>(-1)),
551 font_size(0),
552 baseline_offset(0),
553 baseline_type(0),
554 font_style(0),
555 strike(false),
556 diagonal_strike(false),
557 underline(false) {
560 TextRunHarfBuzz::~TextRunHarfBuzz() {}
562 Range TextRunHarfBuzz::CharRangeToGlyphRange(const Range& char_range) const {
563 DCHECK(range.Contains(char_range));
564 DCHECK(!char_range.is_reversed());
565 DCHECK(!char_range.is_empty());
567 Range start_glyphs;
568 Range end_glyphs;
569 Range temp_range;
570 GetClusterAt(char_range.start(), &temp_range, &start_glyphs);
571 GetClusterAt(char_range.end() - 1, &temp_range, &end_glyphs);
573 return is_rtl ? Range(end_glyphs.start(), start_glyphs.end()) :
574 Range(start_glyphs.start(), end_glyphs.end());
577 size_t TextRunHarfBuzz::CountMissingGlyphs() const {
578 static const int kMissingGlyphId = 0;
579 size_t missing = 0;
580 for (size_t i = 0; i < glyph_count; ++i)
581 missing += (glyphs[i] == kMissingGlyphId) ? 1 : 0;
582 return missing;
585 void TextRunHarfBuzz::GetClusterAt(size_t pos,
586 Range* chars,
587 Range* glyphs) const {
588 DCHECK(range.Contains(Range(pos, pos + 1)));
589 DCHECK(chars);
590 DCHECK(glyphs);
592 if (glyph_count == 0) {
593 *chars = range;
594 *glyphs = Range();
595 return;
598 if (is_rtl) {
599 GetClusterAtImpl(pos, range, glyph_to_char.rbegin(), glyph_to_char.rend(),
600 true, chars, glyphs);
601 return;
604 GetClusterAtImpl(pos, range, glyph_to_char.begin(), glyph_to_char.end(),
605 false, chars, glyphs);
608 RangeF TextRunHarfBuzz::GetGraphemeBounds(
609 base::i18n::BreakIterator* grapheme_iterator,
610 size_t text_index) {
611 DCHECK_LT(text_index, range.end());
612 if (glyph_count == 0)
613 return RangeF(preceding_run_widths, preceding_run_widths + width);
615 Range chars;
616 Range glyphs;
617 GetClusterAt(text_index, &chars, &glyphs);
618 const float cluster_begin_x = positions[glyphs.start()].x();
619 const float cluster_end_x = glyphs.end() < glyph_count ?
620 positions[glyphs.end()].x() : SkFloatToScalar(width);
622 // A cluster consists of a number of code points and corresponds to a number
623 // of glyphs that should be drawn together. A cluster can contain multiple
624 // graphemes. In order to place the cursor at a grapheme boundary inside the
625 // cluster, we simply divide the cluster width by the number of graphemes.
626 if (chars.length() > 1 && grapheme_iterator) {
627 int before = 0;
628 int total = 0;
629 for (size_t i = chars.start(); i < chars.end(); ++i) {
630 if (grapheme_iterator->IsGraphemeBoundary(i)) {
631 if (i < text_index)
632 ++before;
633 ++total;
636 DCHECK_GT(total, 0);
637 if (total > 1) {
638 if (is_rtl)
639 before = total - before - 1;
640 DCHECK_GE(before, 0);
641 DCHECK_LT(before, total);
642 const int cluster_width = cluster_end_x - cluster_begin_x;
643 const int grapheme_begin_x = cluster_begin_x + static_cast<int>(0.5f +
644 cluster_width * before / static_cast<float>(total));
645 const int grapheme_end_x = cluster_begin_x + static_cast<int>(0.5f +
646 cluster_width * (before + 1) / static_cast<float>(total));
647 return RangeF(preceding_run_widths + grapheme_begin_x,
648 preceding_run_widths + grapheme_end_x);
652 return RangeF(preceding_run_widths + cluster_begin_x,
653 preceding_run_widths + cluster_end_x);
656 SkScalar TextRunHarfBuzz::GetGlyphWidthForCharRange(
657 const Range& char_range) const {
658 if (char_range.is_empty())
659 return 0;
661 DCHECK(range.Contains(char_range));
662 Range glyph_range = CharRangeToGlyphRange(char_range);
664 // The |glyph_range| might be empty or invalid on Windows if a multi-character
665 // grapheme is divided into different runs (e.g., there are two font sizes or
666 // colors for a single glyph). In this case it might cause the browser crash,
667 // see crbug.com/526234.
668 if (glyph_range.start() >= glyph_range.end()) {
669 NOTREACHED() << "The glyph range is empty or invalid! Its char range: ["
670 << char_range.start() << ", " << char_range.end()
671 << "], and its glyph range: [" << glyph_range.start() << ", "
672 << glyph_range.end() << "].";
673 return 0;
676 return ((glyph_range.end() == glyph_count)
677 ? SkFloatToScalar(width)
678 : positions[glyph_range.end()].x()) -
679 positions[glyph_range.start()].x();
682 TextRunList::TextRunList() : width_(0.0f) {}
684 TextRunList::~TextRunList() {}
686 void TextRunList::Reset() {
687 runs_.clear();
688 width_ = 0.0f;
691 void TextRunList::InitIndexMap() {
692 if (runs_.size() == 1) {
693 visual_to_logical_ = logical_to_visual_ = std::vector<int32_t>(1, 0);
694 return;
696 const size_t num_runs = runs_.size();
697 std::vector<UBiDiLevel> levels(num_runs);
698 for (size_t i = 0; i < num_runs; ++i)
699 levels[i] = runs_[i]->level;
700 visual_to_logical_.resize(num_runs);
701 ubidi_reorderVisual(&levels[0], num_runs, &visual_to_logical_[0]);
702 logical_to_visual_.resize(num_runs);
703 ubidi_reorderLogical(&levels[0], num_runs, &logical_to_visual_[0]);
706 void TextRunList::ComputePrecedingRunWidths() {
707 // Precalculate run width information.
708 width_ = 0.0f;
709 for (size_t i = 0; i < runs_.size(); ++i) {
710 TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
711 run->preceding_run_widths = width_;
712 width_ += run->width;
716 size_t TextRunList::GetRunIndexAt(size_t position) const {
717 for (size_t i = 0; i < runs_.size(); ++i) {
718 if (runs_[i]->range.start() <= position && runs_[i]->range.end() > position)
719 return i;
721 return runs_.size();
724 } // namespace internal
726 RenderTextHarfBuzz::RenderTextHarfBuzz()
727 : RenderText(),
728 update_layout_run_list_(false),
729 update_display_run_list_(false),
730 update_grapheme_iterator_(false),
731 update_display_text_(false),
732 glyph_width_for_test_(0u) {
733 set_truncate_length(kMaxTextLength);
736 RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
738 scoped_ptr<RenderText> RenderTextHarfBuzz::CreateInstanceOfSameType() const {
739 return make_scoped_ptr(new RenderTextHarfBuzz);
742 bool RenderTextHarfBuzz::MultilineSupported() const {
743 return true;
746 const base::string16& RenderTextHarfBuzz::GetDisplayText() {
747 // TODO(oshima): Consider supporting eliding multi-line text.
748 // This requires max_line support first.
749 if (multiline() ||
750 elide_behavior() == NO_ELIDE ||
751 elide_behavior() == FADE_TAIL) {
752 // Call UpdateDisplayText to clear |display_text_| and |text_elided_|
753 // on the RenderText class.
754 UpdateDisplayText(0);
755 update_display_text_ = false;
756 display_run_list_.reset();
757 return layout_text();
760 EnsureLayoutRunList();
761 DCHECK(!update_display_text_);
762 return text_elided() ? display_text() : layout_text();
765 Size RenderTextHarfBuzz::GetStringSize() {
766 const SizeF size_f = GetStringSizeF();
767 return Size(std::ceil(size_f.width()), size_f.height());
770 SizeF RenderTextHarfBuzz::GetStringSizeF() {
771 EnsureLayout();
772 return total_size_;
775 SelectionModel RenderTextHarfBuzz::FindCursorPosition(const Point& point) {
776 EnsureLayout();
778 int x = ToTextPoint(point).x();
779 float offset = 0;
780 size_t run_index = GetRunContainingXCoord(x, &offset);
782 internal::TextRunList* run_list = GetRunList();
783 if (run_index >= run_list->size())
784 return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT);
785 const internal::TextRunHarfBuzz& run = *run_list->runs()[run_index];
786 for (size_t i = 0; i < run.glyph_count; ++i) {
787 const SkScalar end =
788 i + 1 == run.glyph_count ? run.width : run.positions[i + 1].x();
789 const SkScalar middle = (end + run.positions[i].x()) / 2;
791 if (offset < middle) {
792 return SelectionModel(DisplayIndexToTextIndex(
793 run.glyph_to_char[i] + (run.is_rtl ? 1 : 0)),
794 (run.is_rtl ? CURSOR_BACKWARD : CURSOR_FORWARD));
796 if (offset < end) {
797 return SelectionModel(DisplayIndexToTextIndex(
798 run.glyph_to_char[i] + (run.is_rtl ? 0 : 1)),
799 (run.is_rtl ? CURSOR_FORWARD : CURSOR_BACKWARD));
802 return EdgeSelectionModel(CURSOR_RIGHT);
805 std::vector<RenderText::FontSpan> RenderTextHarfBuzz::GetFontSpansForTesting() {
806 EnsureLayout();
808 internal::TextRunList* run_list = GetRunList();
809 std::vector<RenderText::FontSpan> spans;
810 for (auto* run : run_list->runs()) {
811 SkString family_name;
812 run->skia_face->getFamilyName(&family_name);
813 Font font(family_name.c_str(), run->font_size);
814 spans.push_back(RenderText::FontSpan(
815 font,
816 Range(DisplayIndexToTextIndex(run->range.start()),
817 DisplayIndexToTextIndex(run->range.end()))));
820 return spans;
823 Range RenderTextHarfBuzz::GetGlyphBounds(size_t index) {
824 EnsureLayout();
825 const size_t run_index =
826 GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD));
827 internal::TextRunList* run_list = GetRunList();
828 // Return edge bounds if the index is invalid or beyond the layout text size.
829 if (run_index >= run_list->size())
830 return Range(GetStringSize().width());
831 const size_t layout_index = TextIndexToDisplayIndex(index);
832 internal::TextRunHarfBuzz* run = run_list->runs()[run_index];
833 RangeF bounds =
834 run->GetGraphemeBounds(GetGraphemeIterator(), layout_index);
835 // If cursor is enabled, extend the last glyph up to the rightmost cursor
836 // position since clients expect them to be contiguous.
837 if (cursor_enabled() && run_index == run_list->size() - 1 &&
838 index == (run->is_rtl ? run->range.start() : run->range.end() - 1))
839 bounds.set_end(std::ceil(bounds.end()));
840 return run->is_rtl ? RangeF(bounds.end(), bounds.start()).Round()
841 : bounds.Round();
844 int RenderTextHarfBuzz::GetDisplayTextBaseline() {
845 EnsureLayout();
846 return lines()[0].baseline;
849 SelectionModel RenderTextHarfBuzz::AdjacentCharSelectionModel(
850 const SelectionModel& selection,
851 VisualCursorDirection direction) {
852 DCHECK(!update_display_run_list_);
854 internal::TextRunList* run_list = GetRunList();
855 internal::TextRunHarfBuzz* run;
857 size_t run_index = GetRunContainingCaret(selection);
858 if (run_index >= run_list->size()) {
859 // The cursor is not in any run: we're at the visual and logical edge.
860 SelectionModel edge = EdgeSelectionModel(direction);
861 if (edge.caret_pos() == selection.caret_pos())
862 return edge;
863 int visual_index = (direction == CURSOR_RIGHT) ? 0 : run_list->size() - 1;
864 run = run_list->runs()[run_list->visual_to_logical(visual_index)];
865 } else {
866 // If the cursor is moving within the current run, just move it by one
867 // grapheme in the appropriate direction.
868 run = run_list->runs()[run_index];
869 size_t caret = selection.caret_pos();
870 bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
871 if (forward_motion) {
872 if (caret < DisplayIndexToTextIndex(run->range.end())) {
873 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
874 return SelectionModel(caret, CURSOR_BACKWARD);
876 } else {
877 if (caret > DisplayIndexToTextIndex(run->range.start())) {
878 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
879 return SelectionModel(caret, CURSOR_FORWARD);
882 // The cursor is at the edge of a run; move to the visually adjacent run.
883 int visual_index = run_list->logical_to_visual(run_index);
884 visual_index += (direction == CURSOR_LEFT) ? -1 : 1;
885 if (visual_index < 0 || visual_index >= static_cast<int>(run_list->size()))
886 return EdgeSelectionModel(direction);
887 run = run_list->runs()[run_list->visual_to_logical(visual_index)];
889 bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
890 return forward_motion ? FirstSelectionModelInsideRun(run) :
891 LastSelectionModelInsideRun(run);
894 SelectionModel RenderTextHarfBuzz::AdjacentWordSelectionModel(
895 const SelectionModel& selection,
896 VisualCursorDirection direction) {
897 if (obscured())
898 return EdgeSelectionModel(direction);
900 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
901 bool success = iter.Init();
902 DCHECK(success);
903 if (!success)
904 return selection;
906 // Match OS specific word break behavior.
907 #if defined(OS_WIN)
908 size_t pos;
909 if (direction == CURSOR_RIGHT) {
910 pos = std::min(selection.caret_pos() + 1, text().length());
911 while (iter.Advance()) {
912 pos = iter.pos();
913 if (iter.IsWord() && pos > selection.caret_pos())
914 break;
916 } else { // direction == CURSOR_LEFT
917 // Notes: We always iterate words from the beginning.
918 // This is probably fast enough for our usage, but we may
919 // want to modify WordIterator so that it can start from the
920 // middle of string and advance backwards.
921 pos = std::max<int>(selection.caret_pos() - 1, 0);
922 while (iter.Advance()) {
923 if (iter.IsWord()) {
924 size_t begin = iter.pos() - iter.GetString().length();
925 if (begin == selection.caret_pos()) {
926 // The cursor is at the beginning of a word.
927 // Move to previous word.
928 break;
929 } else if (iter.pos() >= selection.caret_pos()) {
930 // The cursor is in the middle or at the end of a word.
931 // Move to the top of current word.
932 pos = begin;
933 break;
935 pos = iter.pos() - iter.GetString().length();
939 return SelectionModel(pos, CURSOR_FORWARD);
940 #else
941 internal::TextRunList* run_list = GetRunList();
942 SelectionModel cur(selection);
943 for (;;) {
944 cur = AdjacentCharSelectionModel(cur, direction);
945 size_t run = GetRunContainingCaret(cur);
946 if (run == run_list->size())
947 break;
948 const bool is_forward =
949 run_list->runs()[run]->is_rtl == (direction == CURSOR_LEFT);
950 size_t cursor = cur.caret_pos();
951 if (is_forward ? iter.IsEndOfWord(cursor) : iter.IsStartOfWord(cursor))
952 break;
954 return cur;
955 #endif
958 std::vector<Rect> RenderTextHarfBuzz::GetSubstringBounds(const Range& range) {
959 DCHECK(!update_display_run_list_);
960 DCHECK(Range(0, text().length()).Contains(range));
961 Range layout_range(TextIndexToDisplayIndex(range.start()),
962 TextIndexToDisplayIndex(range.end()));
963 DCHECK(Range(0, GetDisplayText().length()).Contains(layout_range));
965 std::vector<Rect> rects;
966 if (layout_range.is_empty())
967 return rects;
968 std::vector<Range> bounds;
970 internal::TextRunList* run_list = GetRunList();
972 // Add a Range for each run/selection intersection.
973 for (size_t i = 0; i < run_list->size(); ++i) {
974 internal::TextRunHarfBuzz* run =
975 run_list->runs()[run_list->visual_to_logical(i)];
976 Range intersection = run->range.Intersect(layout_range);
977 if (!intersection.IsValid())
978 continue;
979 DCHECK(!intersection.is_reversed());
980 const size_t left_index =
981 run->is_rtl ? intersection.end() - 1 : intersection.start();
982 const Range leftmost_character_x =
983 run->GetGraphemeBounds(GetGraphemeIterator(), left_index).Round();
984 const size_t right_index =
985 run->is_rtl ? intersection.start() : intersection.end() - 1;
986 const Range rightmost_character_x =
987 run->GetGraphemeBounds(GetGraphemeIterator(), right_index).Round();
988 Range range_x(leftmost_character_x.start(), rightmost_character_x.end());
989 DCHECK(!range_x.is_reversed());
990 if (range_x.is_empty())
991 continue;
993 // Union this with the last range if they're adjacent.
994 DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin());
995 if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) {
996 range_x = Range(bounds.back().GetMin(), range_x.GetMax());
997 bounds.pop_back();
999 bounds.push_back(range_x);
1001 for (Range& bound : bounds) {
1002 std::vector<Rect> current_rects = TextBoundsToViewBounds(bound);
1003 rects.insert(rects.end(), current_rects.begin(), current_rects.end());
1005 return rects;
1008 size_t RenderTextHarfBuzz::TextIndexToDisplayIndex(size_t index) {
1009 return TextIndexToGivenTextIndex(GetDisplayText(), index);
1012 size_t RenderTextHarfBuzz::DisplayIndexToTextIndex(size_t index) {
1013 if (!obscured())
1014 return index;
1015 const size_t text_index = UTF16OffsetToIndex(text(), 0, index);
1016 DCHECK_LE(text_index, text().length());
1017 return text_index;
1020 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index) {
1021 if (index == 0 || index == text().length())
1022 return true;
1023 if (!IsValidLogicalIndex(index))
1024 return false;
1025 base::i18n::BreakIterator* grapheme_iterator = GetGraphemeIterator();
1026 return !grapheme_iterator || grapheme_iterator->IsGraphemeBoundary(index);
1029 void RenderTextHarfBuzz::OnLayoutTextAttributeChanged(bool text_changed) {
1030 update_layout_run_list_ = true;
1031 OnDisplayTextAttributeChanged();
1034 void RenderTextHarfBuzz::OnDisplayTextAttributeChanged() {
1035 update_display_text_ = true;
1036 update_grapheme_iterator_ = true;
1039 void RenderTextHarfBuzz::EnsureLayout() {
1040 EnsureLayoutRunList();
1042 if (update_display_run_list_) {
1043 DCHECK(text_elided());
1044 const base::string16& display_text = GetDisplayText();
1045 display_run_list_.reset(new internal::TextRunList);
1047 if (!display_text.empty()) {
1048 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayout1");
1050 ItemizeTextToRuns(display_text, display_run_list_.get());
1052 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1053 // fixed.
1054 tracked_objects::ScopedTracker tracking_profile(
1055 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 1"));
1056 ShapeRunList(display_text, display_run_list_.get());
1058 update_display_run_list_ = false;
1060 std::vector<internal::Line> empty_lines;
1061 set_lines(&empty_lines);
1064 if (lines().empty()) {
1065 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1066 // fixed.
1067 scoped_ptr<tracked_objects::ScopedTracker> tracking_profile(
1068 new tracked_objects::ScopedTracker(
1069 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 HarfBuzzLineBreaker")));
1071 internal::TextRunList* run_list = GetRunList();
1072 HarfBuzzLineBreaker line_breaker(
1073 display_rect().width(), font_list().GetBaseline(),
1074 std::max(font_list().GetHeight(), min_line_height()),
1075 word_wrap_behavior(), GetDisplayText(),
1076 multiline() ? &GetLineBreaks() : nullptr, *run_list);
1078 tracking_profile.reset();
1080 if (multiline())
1081 line_breaker.ConstructMultiLines();
1082 else
1083 line_breaker.ConstructSingleLine();
1084 std::vector<internal::Line> lines;
1085 line_breaker.FinalizeLines(&lines, &total_size_);
1086 set_lines(&lines);
1090 void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) {
1091 internal::SkiaTextRenderer renderer(canvas);
1092 DrawVisualTextInternal(&renderer);
1095 void RenderTextHarfBuzz::DrawVisualTextInternal(
1096 internal::SkiaTextRenderer* renderer) {
1097 DCHECK(!update_layout_run_list_);
1098 DCHECK(!update_display_run_list_);
1099 DCHECK(!update_display_text_);
1100 if (lines().empty())
1101 return;
1103 ApplyFadeEffects(renderer);
1104 ApplyTextShadows(renderer);
1105 ApplyCompositionAndSelectionStyles();
1107 internal::TextRunList* run_list = GetRunList();
1108 for (size_t i = 0; i < lines().size(); ++i) {
1109 const internal::Line& line = lines()[i];
1110 const Vector2d origin = GetLineOffset(i) + Vector2d(0, line.baseline);
1111 SkScalar preceding_segment_widths = 0;
1112 for (const internal::LineSegment& segment : line.segments) {
1113 const internal::TextRunHarfBuzz& run = *run_list->runs()[segment.run];
1114 renderer->SetTypeface(run.skia_face.get());
1115 renderer->SetTextSize(SkIntToScalar(run.font_size));
1116 renderer->SetFontRenderParams(run.render_params,
1117 subpixel_rendering_suppressed());
1118 Range glyphs_range = run.CharRangeToGlyphRange(segment.char_range);
1119 scoped_ptr<SkPoint[]> positions(new SkPoint[glyphs_range.length()]);
1120 SkScalar offset_x = preceding_segment_widths -
1121 ((glyphs_range.GetMin() != 0)
1122 ? run.positions[glyphs_range.GetMin()].x()
1123 : 0);
1124 for (size_t j = 0; j < glyphs_range.length(); ++j) {
1125 positions[j] = run.positions[(glyphs_range.is_reversed()) ?
1126 (glyphs_range.start() - j) :
1127 (glyphs_range.start() + j)];
1128 positions[j].offset(SkIntToScalar(origin.x()) + offset_x,
1129 SkIntToScalar(origin.y() + run.baseline_offset));
1131 for (BreakList<SkColor>::const_iterator it =
1132 colors().GetBreak(segment.char_range.start());
1133 it != colors().breaks().end() &&
1134 it->first < segment.char_range.end();
1135 ++it) {
1136 const Range intersection =
1137 colors().GetRange(it).Intersect(segment.char_range);
1138 const Range colored_glyphs = run.CharRangeToGlyphRange(intersection);
1139 // The range may be empty if a portion of a multi-character grapheme is
1140 // selected, yielding two colors for a single glyph. For now, this just
1141 // paints the glyph with a single style, but it should paint it twice,
1142 // clipped according to selection bounds. See http://crbug.com/366786
1143 if (colored_glyphs.is_empty())
1144 continue;
1146 renderer->SetForegroundColor(it->second);
1147 renderer->DrawPosText(
1148 &positions[colored_glyphs.start() - glyphs_range.start()],
1149 &run.glyphs[colored_glyphs.start()], colored_glyphs.length());
1150 int start_x = SkScalarRoundToInt(
1151 positions[colored_glyphs.start() - glyphs_range.start()].x());
1152 int end_x = SkScalarRoundToInt(
1153 (colored_glyphs.end() == glyphs_range.end())
1154 ? (SkFloatToScalar(segment.width()) + preceding_segment_widths +
1155 SkIntToScalar(origin.x()))
1156 : positions[colored_glyphs.end() - glyphs_range.start()].x());
1157 renderer->DrawDecorations(start_x, origin.y(), end_x - start_x,
1158 run.underline, run.strike,
1159 run.diagonal_strike);
1161 preceding_segment_widths += SkFloatToScalar(segment.width());
1165 renderer->EndDiagonalStrike();
1167 UndoCompositionAndSelectionStyles();
1170 size_t RenderTextHarfBuzz::GetRunContainingCaret(
1171 const SelectionModel& caret) {
1172 DCHECK(!update_display_run_list_);
1173 size_t layout_position = TextIndexToDisplayIndex(caret.caret_pos());
1174 LogicalCursorDirection affinity = caret.caret_affinity();
1175 internal::TextRunList* run_list = GetRunList();
1176 for (size_t i = 0; i < run_list->size(); ++i) {
1177 internal::TextRunHarfBuzz* run = run_list->runs()[i];
1178 if (RangeContainsCaret(run->range, layout_position, affinity))
1179 return i;
1181 return run_list->size();
1184 size_t RenderTextHarfBuzz::GetRunContainingXCoord(float x,
1185 float* offset) const {
1186 DCHECK(!update_display_run_list_);
1187 const internal::TextRunList* run_list = GetRunList();
1188 if (x < 0)
1189 return run_list->size();
1190 // Find the text run containing the argument point (assumed already offset).
1191 float current_x = 0;
1192 for (size_t i = 0; i < run_list->size(); ++i) {
1193 size_t run = run_list->visual_to_logical(i);
1194 current_x += run_list->runs()[run]->width;
1195 if (x < current_x) {
1196 *offset = x - (current_x - run_list->runs()[run]->width);
1197 return run;
1200 return run_list->size();
1203 SelectionModel RenderTextHarfBuzz::FirstSelectionModelInsideRun(
1204 const internal::TextRunHarfBuzz* run) {
1205 size_t position = DisplayIndexToTextIndex(run->range.start());
1206 position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD);
1207 return SelectionModel(position, CURSOR_BACKWARD);
1210 SelectionModel RenderTextHarfBuzz::LastSelectionModelInsideRun(
1211 const internal::TextRunHarfBuzz* run) {
1212 size_t position = DisplayIndexToTextIndex(run->range.end());
1213 position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD);
1214 return SelectionModel(position, CURSOR_FORWARD);
1217 void RenderTextHarfBuzz::ItemizeTextToRuns(
1218 const base::string16& text,
1219 internal::TextRunList* run_list_out) {
1220 DCHECK_NE(0U, text.length());
1222 // If ICU fails to itemize the text, we create a run that spans the entire
1223 // text. This is needed because leaving the runs set empty causes some clients
1224 // to misbehave since they expect non-zero text metrics from a non-empty text.
1225 base::i18n::BiDiLineIterator bidi_iterator;
1226 if (!bidi_iterator.Open(text, GetTextDirection(text))) {
1227 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
1228 run->range = Range(0, text.length());
1229 run_list_out->add(run);
1230 run_list_out->InitIndexMap();
1231 return;
1234 // Temporarily apply composition underlines and selection colors.
1235 ApplyCompositionAndSelectionStyles();
1237 // Build the run list from the script items and ranged styles and baselines.
1238 // Use an empty color BreakList to avoid breaking runs at color boundaries.
1239 BreakList<SkColor> empty_colors;
1240 empty_colors.SetMax(text.length());
1241 DCHECK_LE(text.size(), baselines().max());
1242 for (const BreakList<bool>& style : styles())
1243 DCHECK_LE(text.size(), style.max());
1244 internal::StyleIterator style(empty_colors, baselines(), styles());
1246 for (size_t run_break = 0; run_break < text.length();) {
1247 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
1248 run->range.set_start(run_break);
1249 run->font_style = (style.style(BOLD) ? Font::BOLD : 0) |
1250 (style.style(ITALIC) ? Font::ITALIC : 0);
1251 run->baseline_type = style.baseline();
1252 run->strike = style.style(STRIKE);
1253 run->diagonal_strike = style.style(DIAGONAL_STRIKE);
1254 run->underline = style.style(UNDERLINE);
1255 int32 script_item_break = 0;
1256 bidi_iterator.GetLogicalRun(run_break, &script_item_break, &run->level);
1257 // Odd BiDi embedding levels correspond to RTL runs.
1258 run->is_rtl = (run->level % 2) == 1;
1259 // Find the length and script of this script run.
1260 script_item_break = ScriptInterval(text, run_break,
1261 script_item_break - run_break, &run->script) + run_break;
1263 // Find the next break and advance the iterators as needed.
1264 const size_t new_run_break = std::min(
1265 static_cast<size_t>(script_item_break),
1266 TextIndexToGivenTextIndex(text, style.GetRange().end()));
1267 CHECK_NE(new_run_break, run_break)
1268 << "It must proceed! " << text << " " << run_break;
1269 run_break = new_run_break;
1271 // Break runs at certain characters that need to be rendered separately to
1272 // prevent either an unusual character from forcing a fallback font on the
1273 // entire run, or brackets from being affected by a fallback font.
1274 // http://crbug.com/278913, http://crbug.com/396776
1275 if (run_break > run->range.start())
1276 run_break = FindRunBreakingCharacter(text, run->range.start(), run_break);
1278 DCHECK(IsValidCodePointIndex(text, run_break));
1279 style.UpdatePosition(DisplayIndexToTextIndex(run_break));
1280 run->range.set_end(run_break);
1282 run_list_out->add(run);
1285 // Undo the temporarily applied composition underlines and selection colors.
1286 UndoCompositionAndSelectionStyles();
1288 run_list_out->InitIndexMap();
1291 bool RenderTextHarfBuzz::CompareFamily(
1292 const base::string16& text,
1293 const std::string& family,
1294 const gfx::FontRenderParams& render_params,
1295 internal::TextRunHarfBuzz* run,
1296 std::string* best_family,
1297 gfx::FontRenderParams* best_render_params,
1298 size_t* best_missing_glyphs) {
1299 if (!ShapeRunWithFont(text, family, render_params, run))
1300 return false;
1302 const size_t missing_glyphs = run->CountMissingGlyphs();
1303 if (missing_glyphs < *best_missing_glyphs) {
1304 *best_family = family;
1305 *best_render_params = render_params;
1306 *best_missing_glyphs = missing_glyphs;
1308 return missing_glyphs == 0;
1311 void RenderTextHarfBuzz::ShapeRunList(const base::string16& text,
1312 internal::TextRunList* run_list) {
1313 for (auto* run : run_list->runs())
1314 ShapeRun(text, run);
1315 run_list->ComputePrecedingRunWidths();
1318 void RenderTextHarfBuzz::ShapeRun(const base::string16& text,
1319 internal::TextRunHarfBuzz* run) {
1320 const Font& primary_font = font_list().GetPrimaryFont();
1321 const std::string primary_family = primary_font.GetFontName();
1322 run->font_size = primary_font.GetFontSize();
1323 run->baseline_offset = 0;
1324 if (run->baseline_type != NORMAL_BASELINE) {
1325 // Calculate a slightly smaller font. The ratio here is somewhat arbitrary.
1326 // Proportions from 5/9 to 5/7 all look pretty good.
1327 const float ratio = 5.0f / 9.0f;
1328 run->font_size = gfx::ToRoundedInt(primary_font.GetFontSize() * ratio);
1329 switch (run->baseline_type) {
1330 case SUPERSCRIPT:
1331 run->baseline_offset =
1332 primary_font.GetCapHeight() - primary_font.GetHeight();
1333 break;
1334 case SUPERIOR:
1335 run->baseline_offset =
1336 gfx::ToRoundedInt(primary_font.GetCapHeight() * ratio) -
1337 primary_font.GetCapHeight();
1338 break;
1339 case SUBSCRIPT:
1340 run->baseline_offset =
1341 primary_font.GetHeight() - primary_font.GetBaseline();
1342 break;
1343 case INFERIOR: // Fall through.
1344 default:
1345 break;
1349 std::string best_family;
1350 FontRenderParams best_render_params;
1351 size_t best_missing_glyphs = std::numeric_limits<size_t>::max();
1353 for (const Font& font : font_list().GetFonts()) {
1354 if (CompareFamily(text, font.GetFontName(), font.GetFontRenderParams(),
1355 run, &best_family, &best_render_params,
1356 &best_missing_glyphs))
1357 return;
1360 #if defined(OS_WIN)
1361 Font uniscribe_font;
1362 std::string uniscribe_family;
1363 const base::char16* run_text = &(text[run->range.start()]);
1364 if (GetUniscribeFallbackFont(primary_font, run_text, run->range.length(),
1365 &uniscribe_font)) {
1366 uniscribe_family = uniscribe_font.GetFontName();
1367 if (CompareFamily(text, uniscribe_family,
1368 uniscribe_font.GetFontRenderParams(), run,
1369 &best_family, &best_render_params, &best_missing_glyphs))
1370 return;
1372 #endif
1374 std::vector<std::string> fallback_families =
1375 GetFallbackFontFamilies(primary_family);
1377 #if defined(OS_WIN)
1378 // Append fonts in the fallback list of the Uniscribe font.
1379 if (!uniscribe_family.empty()) {
1380 std::vector<std::string> uniscribe_fallbacks =
1381 GetFallbackFontFamilies(uniscribe_family);
1382 fallback_families.insert(fallback_families.end(),
1383 uniscribe_fallbacks.begin(), uniscribe_fallbacks.end());
1386 // Add Segoe UI and its associated linked fonts to the fallback font list to
1387 // ensure that the fallback list covers the basic cases.
1388 // http://crbug.com/467459. On some Windows configurations the default font
1389 // could be a raster font like System, which would not give us a reasonable
1390 // fallback font list.
1391 if (!base::LowerCaseEqualsASCII(primary_family, "segoe ui") &&
1392 !base::LowerCaseEqualsASCII(uniscribe_family, "segoe ui")) {
1393 std::vector<std::string> default_fallback_families =
1394 GetFallbackFontFamilies("Segoe UI");
1395 fallback_families.insert(fallback_families.end(),
1396 default_fallback_families.begin(), default_fallback_families.end());
1398 #endif
1400 // Use a set to track the fallback fonts and avoid duplicate entries.
1401 std::set<std::string, CaseInsensitiveCompare> fallback_fonts;
1403 // Try shaping with the fallback fonts.
1404 for (const auto& family : fallback_families) {
1405 if (family == primary_family)
1406 continue;
1407 #if defined(OS_WIN)
1408 if (family == uniscribe_family)
1409 continue;
1410 #endif
1411 if (fallback_fonts.find(family) != fallback_fonts.end())
1412 continue;
1414 fallback_fonts.insert(family);
1416 FontRenderParamsQuery query;
1417 query.families.push_back(family);
1418 query.pixel_size = run->font_size;
1419 query.style = run->font_style;
1420 FontRenderParams fallback_render_params = GetFontRenderParams(query, NULL);
1421 if (CompareFamily(text, family, fallback_render_params, run, &best_family,
1422 &best_render_params, &best_missing_glyphs))
1423 return;
1426 if (!best_family.empty() &&
1427 (best_family == run->family ||
1428 ShapeRunWithFont(text, best_family, best_render_params, run)))
1429 return;
1431 run->glyph_count = 0;
1432 run->width = 0.0f;
1435 bool RenderTextHarfBuzz::ShapeRunWithFont(const base::string16& text,
1436 const std::string& font_family,
1437 const FontRenderParams& params,
1438 internal::TextRunHarfBuzz* run) {
1439 skia::RefPtr<SkTypeface> skia_face =
1440 internal::CreateSkiaTypeface(font_family, run->font_style);
1441 if (skia_face == NULL)
1442 return false;
1443 run->skia_face = skia_face;
1444 run->family = font_family;
1445 run->render_params = params;
1447 hb_font_t* harfbuzz_font = CreateHarfBuzzFont(
1448 run->skia_face.get(), SkIntToScalar(run->font_size), run->render_params,
1449 subpixel_rendering_suppressed());
1451 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
1452 // buffer holds our text, run information to be used by the shaping engine,
1453 // and the resulting glyph data.
1454 hb_buffer_t* buffer = hb_buffer_create();
1455 hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16*>(text.c_str()),
1456 text.length(), run->range.start(), run->range.length());
1457 hb_buffer_set_script(buffer, ICUScriptToHBScript(run->script));
1458 hb_buffer_set_direction(buffer,
1459 run->is_rtl ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
1460 // TODO(ckocagil): Should we determine the actual language?
1461 hb_buffer_set_language(buffer, hb_language_get_default());
1464 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1465 // fixed.
1466 tracked_objects::ScopedTracker tracking_profile(
1467 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 hb_shape()"));
1469 // Shape the text.
1470 hb_shape(harfbuzz_font, buffer, NULL, 0);
1473 // Populate the run fields with the resulting glyph data in the buffer.
1474 unsigned int glyph_count = 0;
1475 hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(buffer, &glyph_count);
1476 run->glyph_count = glyph_count;
1477 hb_glyph_position_t* hb_positions =
1478 hb_buffer_get_glyph_positions(buffer, NULL);
1479 run->glyphs.reset(new uint16[run->glyph_count]);
1480 run->glyph_to_char.resize(run->glyph_count);
1481 run->positions.reset(new SkPoint[run->glyph_count]);
1482 run->width = 0.0f;
1484 for (size_t i = 0; i < run->glyph_count; ++i) {
1485 DCHECK_LE(infos[i].codepoint, std::numeric_limits<uint16>::max());
1486 run->glyphs[i] = static_cast<uint16>(infos[i].codepoint);
1487 run->glyph_to_char[i] = infos[i].cluster;
1488 const SkScalar x_offset = SkFixedToScalar(hb_positions[i].x_offset);
1489 const SkScalar y_offset = SkFixedToScalar(hb_positions[i].y_offset);
1490 run->positions[i].set(run->width + x_offset, -y_offset);
1491 run->width += (glyph_width_for_test_ > 0)
1492 ? glyph_width_for_test_
1493 : SkFixedToFloat(hb_positions[i].x_advance);
1494 // Round run widths if subpixel positioning is off to match native behavior.
1495 if (!run->render_params.subpixel_positioning)
1496 run->width = std::floor(run->width + 0.5f);
1499 hb_buffer_destroy(buffer);
1500 hb_font_destroy(harfbuzz_font);
1501 return true;
1504 void RenderTextHarfBuzz::EnsureLayoutRunList() {
1505 if (update_layout_run_list_) {
1506 layout_run_list_.Reset();
1508 const base::string16& text = layout_text();
1509 if (!text.empty()) {
1510 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayoutRunList");
1511 ItemizeTextToRuns(text, &layout_run_list_);
1513 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1514 // fixed.
1515 tracked_objects::ScopedTracker tracking_profile(
1516 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 2"));
1517 ShapeRunList(text, &layout_run_list_);
1520 std::vector<internal::Line> empty_lines;
1521 set_lines(&empty_lines);
1522 display_run_list_.reset();
1523 update_display_text_ = true;
1524 update_layout_run_list_ = false;
1526 if (update_display_text_) {
1527 UpdateDisplayText(multiline() ? 0 : layout_run_list_.width());
1528 update_display_text_ = false;
1529 update_display_run_list_ = text_elided();
1533 base::i18n::BreakIterator* RenderTextHarfBuzz::GetGraphemeIterator() {
1534 if (update_grapheme_iterator_) {
1535 update_grapheme_iterator_ = false;
1536 grapheme_iterator_.reset(new base::i18n::BreakIterator(
1537 GetDisplayText(),
1538 base::i18n::BreakIterator::BREAK_CHARACTER));
1539 if (!grapheme_iterator_->Init())
1540 grapheme_iterator_.reset();
1542 return grapheme_iterator_.get();
1545 internal::TextRunList* RenderTextHarfBuzz::GetRunList() {
1546 DCHECK(!update_layout_run_list_);
1547 DCHECK(!update_display_run_list_);
1548 return text_elided() ? display_run_list_.get() : &layout_run_list_;
1551 const internal::TextRunList* RenderTextHarfBuzz::GetRunList() const {
1552 return const_cast<RenderTextHarfBuzz*>(this)->GetRunList();
1555 } // namespace gfx