RenderTextHarfBuzz no longer ignores its specified text direction.
[chromium-blink-merge.git] / ui / gfx / render_text_harfbuzz.cc
blob2274c7ccc231c8001efad5d37de9f5ddeac00fad
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 using gfx::internal::RoundRangeF;
37 namespace gfx {
39 namespace {
41 // Text length limit. Longer strings are slow and not fully tested.
42 const size_t kMaxTextLength = 10000;
44 // The maximum number of scripts a Unicode character can belong to. This value
45 // is arbitrarily chosen to be a good limit because it is unlikely for a single
46 // character to belong to more scripts.
47 const size_t kMaxScripts = 5;
49 // Returns true if characters of |block_code| may trigger font fallback.
50 // Dingbats and emoticons can be rendered through the color emoji font file,
51 // therefore it needs to be trigerred as fallbacks. See crbug.com/448909
52 bool IsUnusualBlockCode(UBlockCode block_code) {
53 return block_code == UBLOCK_GEOMETRIC_SHAPES ||
54 block_code == UBLOCK_MISCELLANEOUS_SYMBOLS;
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_INHERITED,
94 // i.e. the more specific one. Otherwise returns USCRIPT_INVALID_CODE.
95 UScriptCode ScriptIntersect(UScriptCode first, UScriptCode second) {
96 if (first == second || second == USCRIPT_INHERITED)
97 return first;
98 if (first == USCRIPT_INHERITED)
99 return second;
100 return USCRIPT_INVALID_CODE;
103 // Writes the script and the script extensions of the character with the
104 // Unicode |codepoint|. Returns the number of written scripts.
105 int GetScriptExtensions(UChar32 codepoint, UScriptCode* scripts) {
106 UErrorCode icu_error = U_ZERO_ERROR;
107 // ICU documentation incorrectly states that the result of
108 // |uscript_getScriptExtensions| will contain the regular script property.
109 // Write the character's script property to the first element.
110 scripts[0] = uscript_getScript(codepoint, &icu_error);
111 if (U_FAILURE(icu_error))
112 return 0;
113 // Fill the rest of |scripts| with the extensions.
114 int count = uscript_getScriptExtensions(codepoint, scripts + 1,
115 kMaxScripts - 1, &icu_error);
116 if (U_FAILURE(icu_error))
117 count = 0;
118 return count + 1;
121 // Intersects the script extensions set of |codepoint| with |result| and writes
122 // to |result|, reading and updating |result_size|.
123 void ScriptSetIntersect(UChar32 codepoint,
124 UScriptCode* result,
125 size_t* result_size) {
126 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
127 int count = GetScriptExtensions(codepoint, scripts);
129 size_t out_size = 0;
131 for (size_t i = 0; i < *result_size; ++i) {
132 for (int j = 0; j < count; ++j) {
133 UScriptCode intersection = ScriptIntersect(result[i], scripts[j]);
134 if (intersection != USCRIPT_INVALID_CODE) {
135 result[out_size++] = intersection;
136 break;
141 *result_size = out_size;
144 // Find the longest sequence of characters from 0 and up to |length| that
145 // have at least one common UScriptCode value. Writes the common script value to
146 // |script| and returns the length of the sequence. Takes the characters' script
147 // extensions into account. http://www.unicode.org/reports/tr24/#ScriptX
149 // Consider 3 characters with the script values {Kana}, {Hira, Kana}, {Kana}.
150 // Without script extensions only the first script in each set would be taken
151 // into account, resulting in 3 runs where 1 would be enough.
152 // TODO(ckocagil): Write a unit test for the case above.
153 int ScriptInterval(const base::string16& text,
154 size_t start,
155 size_t length,
156 UScriptCode* script) {
157 DCHECK_GT(length, 0U);
159 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
161 base::i18n::UTF16CharIterator char_iterator(text.c_str() + start, length);
162 size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts);
163 *script = scripts[0];
165 while (char_iterator.Advance()) {
166 // Special handling to merge white space into the previous run.
167 if (u_isUWhiteSpace(char_iterator.get()))
168 continue;
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 WordWrapBehavior word_wrap_behavior,
227 const base::string16& text,
228 const BreakList<size_t>* words,
229 const internal::TextRunList& run_list)
230 : max_width_((max_width == 0) ? SK_ScalarMax : SkIntToScalar(max_width)),
231 min_baseline_(min_baseline),
232 min_height_(min_height),
233 word_wrap_behavior_(word_wrap_behavior),
234 text_(text),
235 words_(words),
236 run_list_(run_list),
237 max_descent_(0),
238 max_ascent_(0),
239 text_x_(0),
240 available_width_(max_width_) {
241 AdvanceLine();
244 // Constructs a single line for |text_| using |run_list_|.
245 void ConstructSingleLine() {
246 for (size_t i = 0; i < run_list_.size(); i++) {
247 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[i]);
248 internal::LineSegment segment;
249 segment.run = i;
250 segment.char_range = run.range;
251 segment.x_range = Range(SkScalarCeilToInt(text_x_),
252 SkScalarCeilToInt(text_x_ + run.width));
253 segment.width = run.width;
254 AddLineSegment(segment);
258 // Constructs multiple lines for |text_| based on words iteration approach.
259 void ConstructMultiLines() {
260 DCHECK(words_);
261 for (auto iter = words_->breaks().begin(); iter != words_->breaks().end();
262 iter++) {
263 const Range word_range = words_->GetRange(iter);
264 std::vector<internal::LineSegment> word_segments;
265 SkScalar word_width = GetWordWidth(word_range, &word_segments);
267 // If the last word is '\n', we should advance a new line after adding
268 // the word to the current line.
269 bool new_line = false;
270 if (!word_segments.empty() &&
271 text_[word_segments.back().char_range.start()] == '\n') {
272 new_line = true;
273 word_width -= word_segments.back().width;
274 word_segments.pop_back();
277 // If the word is not the first word in the line and it can't fit into
278 // the current line, advance a new line.
279 if (word_width > available_width_ && available_width_ != max_width_)
280 AdvanceLine();
281 if (!word_segments.empty())
282 AddWordToLine(word_segments);
283 if (new_line)
284 AdvanceLine();
288 // Finishes line breaking and outputs the results. Can be called at most once.
289 void FinalizeLines(std::vector<internal::Line>* lines, SizeF* size) {
290 DCHECK(!lines_.empty());
291 // Add an empty line to finish the line size calculation and remove it.
292 AdvanceLine();
293 lines_.pop_back();
294 *size = total_size_;
295 lines->swap(lines_);
298 private:
299 // A (line index, segment index) pair that specifies a segment in |lines_|.
300 typedef std::pair<size_t, size_t> SegmentHandle;
302 internal::LineSegment* SegmentFromHandle(const SegmentHandle& handle) {
303 return &lines_[handle.first].segments[handle.second];
306 // Finishes the size calculations of the last Line in |lines_|. Adds a new
307 // Line to the back of |lines_|.
308 void AdvanceLine() {
309 if (!lines_.empty()) {
310 internal::Line* line = &lines_.back();
311 std::sort(line->segments.begin(), line->segments.end(),
312 [this](const internal::LineSegment& s1,
313 const internal::LineSegment& s2) -> bool {
314 return run_list_.logical_to_visual(s1.run) <
315 run_list_.logical_to_visual(s2.run);
317 line->size.set_height(std::max(min_height_, max_descent_ + max_ascent_));
318 line->baseline = std::max(min_baseline_, SkScalarRoundToInt(max_ascent_));
319 line->preceding_heights = std::ceil(total_size_.height());
320 total_size_.set_height(total_size_.height() + line->size.height());
321 total_size_.set_width(std::max(total_size_.width(), line->size.width()));
323 max_descent_ = 0;
324 max_ascent_ = 0;
325 available_width_ = max_width_;
326 lines_.push_back(internal::Line());
329 // Adds word to the current line. A word may contain multiple segments. If the
330 // word is the first word in line and its width exceeds |available_width_|,
331 // ignore/truncate/wrap it according to |word_wrap_behavior_|.
332 void AddWordToLine(const std::vector<internal::LineSegment>& word_segments) {
333 DCHECK(!lines_.empty());
334 DCHECK(!word_segments.empty());
336 bool has_truncated = false;
337 for (const internal::LineSegment& segment : word_segments) {
338 if (has_truncated)
339 break;
340 if (segment.width <= available_width_ ||
341 word_wrap_behavior_ == IGNORE_LONG_WORDS) {
342 AddLineSegment(segment);
343 } else {
344 DCHECK(word_wrap_behavior_ == TRUNCATE_LONG_WORDS ||
345 word_wrap_behavior_ == WRAP_LONG_WORDS);
346 has_truncated = (word_wrap_behavior_ == TRUNCATE_LONG_WORDS);
348 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[segment.run]);
349 internal::LineSegment remaining_segment = segment;
350 while (!remaining_segment.char_range.is_empty()) {
351 size_t cutoff_pos = GetCutoffPos(remaining_segment);
352 SkScalar width = run.GetGlyphWidthForCharRange(
353 Range(remaining_segment.char_range.start(), cutoff_pos));
354 if (width > 0) {
355 internal::LineSegment cut_segment;
356 cut_segment.run = remaining_segment.run;
357 cut_segment.char_range =
358 Range(remaining_segment.char_range.start(), cutoff_pos);
359 cut_segment.width = width;
360 cut_segment.x_range = Range(remaining_segment.x_range.start(),
361 SkScalarCeilToInt(text_x_ + width));
362 AddLineSegment(cut_segment);
363 // Updates old segment range.
364 remaining_segment.char_range.set_start(cutoff_pos);
365 remaining_segment.x_range.set_start(SkScalarCeilToInt(text_x_));
366 remaining_segment.width -= width;
368 if (has_truncated)
369 break;
370 if (!remaining_segment.char_range.is_empty())
371 AdvanceLine();
377 // Add a line segment to the current line. Note that, in order to keep the
378 // visual order correct for ltr and rtl language, we need to merge segments
379 // that belong to the same run.
380 void AddLineSegment(const internal::LineSegment& segment) {
381 DCHECK(!lines_.empty());
382 internal::Line* line = &lines_.back();
383 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[segment.run]);
384 if (!line->segments.empty()) {
385 internal::LineSegment& last_segment = line->segments.back();
386 // Merge segments that belong to the same run.
387 if (last_segment.run == segment.run) {
388 DCHECK_EQ(last_segment.char_range.end(), segment.char_range.start());
389 DCHECK_EQ(last_segment.x_range.end(), segment.x_range.start());
390 last_segment.char_range.set_end(segment.char_range.end());
391 last_segment.width += segment.width;
392 last_segment.x_range.set_end(
393 SkScalarCeilToInt(text_x_ + segment.width));
394 if (run.is_rtl && last_segment.char_range.end() == run.range.end())
395 UpdateRTLSegmentRanges();
396 line->size.set_width(line->size.width() + segment.width);
397 text_x_ += segment.width;
398 available_width_ -= segment.width;
399 return;
402 line->segments.push_back(segment);
404 SkPaint paint;
405 paint.setTypeface(run.skia_face.get());
406 paint.setTextSize(SkIntToScalar(run.font_size));
407 paint.setAntiAlias(run.render_params.antialiasing);
408 SkPaint::FontMetrics metrics;
409 paint.getFontMetrics(&metrics);
411 line->size.set_width(line->size.width() + segment.width);
412 // TODO(dschuyler): Account for stylized baselines in string sizing.
413 max_descent_ = std::max(max_descent_, metrics.fDescent);
414 // fAscent is always negative.
415 max_ascent_ = std::max(max_ascent_, -metrics.fAscent);
417 if (run.is_rtl) {
418 rtl_segments_.push_back(
419 SegmentHandle(lines_.size() - 1, line->segments.size() - 1));
420 // If this is the last segment of an RTL run, reprocess the text-space x
421 // ranges of all segments from the run.
422 if (segment.char_range.end() == run.range.end())
423 UpdateRTLSegmentRanges();
425 text_x_ += segment.width;
426 available_width_ -= segment.width;
429 // Finds the end position |end_pos| in |segment| where the preceding width is
430 // no larger than |available_width_|.
431 size_t GetCutoffPos(const internal::LineSegment& segment) const {
432 DCHECK(!segment.char_range.is_empty());
433 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[segment.run]);
434 size_t end_pos = segment.char_range.start();
435 SkScalar width = 0;
436 while (end_pos < segment.char_range.end()) {
437 const SkScalar char_width =
438 run.GetGlyphWidthForCharRange(Range(end_pos, end_pos + 1));
439 if (width + char_width > available_width_)
440 break;
441 width += char_width;
442 end_pos++;
445 const size_t valid_end_pos = FindValidBoundaryBefore(text_, end_pos);
446 if (end_pos != valid_end_pos) {
447 end_pos = valid_end_pos;
448 width = run.GetGlyphWidthForCharRange(
449 Range(segment.char_range.start(), end_pos));
452 // |max_width_| might be smaller than a single character. In this case we
453 // need to put at least one character in the line. Note that, we should
454 // not separate surrogate pair or combining characters.
455 // See RenderTextTest.Multiline_MinWidth for an example.
456 if (width == 0 && available_width_ == max_width_)
457 end_pos = FindValidBoundaryAfter(text_, end_pos + 1);
459 return end_pos;
462 // Gets the glyph width for |word_range|, and splits the |word| into different
463 // segments based on its runs.
464 SkScalar GetWordWidth(const Range& word_range,
465 std::vector<internal::LineSegment>* segments) const {
466 DCHECK(words_);
467 if (word_range.is_empty() || segments == nullptr)
468 return 0;
469 size_t run_start_index = run_list_.GetRunIndexAt(word_range.start());
470 size_t run_end_index = run_list_.GetRunIndexAt(word_range.end() - 1);
471 SkScalar width = 0;
472 for (size_t i = run_start_index; i <= run_end_index; i++) {
473 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[i]);
474 const Range char_range = run.range.Intersect(word_range);
475 DCHECK(!char_range.is_empty());
476 const SkScalar char_width = run.GetGlyphWidthForCharRange(char_range);
477 width += char_width;
479 internal::LineSegment segment;
480 segment.run = i;
481 segment.char_range = char_range;
482 segment.width = char_width;
483 segment.x_range = Range(SkScalarCeilToInt(text_x_ + width - char_width),
484 SkScalarCeilToInt(text_x_ + width));
485 segments->push_back(segment);
487 return width;
490 // RTL runs are broken in logical order but displayed in visual order. To find
491 // the text-space coordinate (where it would fall in a single-line text)
492 // |x_range| of RTL segments, segment widths are applied in reverse order.
493 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}.
494 void UpdateRTLSegmentRanges() {
495 if (rtl_segments_.empty())
496 return;
497 float x = SegmentFromHandle(rtl_segments_[0])->x_range.start();
498 for (size_t i = rtl_segments_.size(); i > 0; --i) {
499 internal::LineSegment* segment = SegmentFromHandle(rtl_segments_[i - 1]);
500 const float segment_width = segment->width;
501 segment->x_range = Range(x, x + segment_width);
502 x += segment_width;
504 rtl_segments_.clear();
507 const SkScalar max_width_;
508 const int min_baseline_;
509 const float min_height_;
510 const WordWrapBehavior word_wrap_behavior_;
511 const base::string16& text_;
512 const BreakList<size_t>* const words_;
513 const internal::TextRunList& run_list_;
515 // Stores the resulting lines.
516 std::vector<internal::Line> lines_;
518 float max_descent_;
519 float max_ascent_;
521 // Text space x coordinates of the next segment to be added.
522 SkScalar text_x_;
523 // Stores available width in the current line.
524 SkScalar available_width_;
526 // Size of the multiline text, not including the currently processed line.
527 SizeF total_size_;
529 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
530 std::vector<SegmentHandle> rtl_segments_;
532 DISALLOW_COPY_AND_ASSIGN(HarfBuzzLineBreaker);
535 // Function object for case insensitive string comparison.
536 struct CaseInsensitiveCompare {
537 bool operator() (const std::string& a, const std::string& b) const {
538 return base::strncasecmp(a.c_str(), b.c_str(), b.length()) < 0;
542 } // namespace
544 namespace internal {
546 Range RoundRangeF(const RangeF& range_f) {
547 return Range(std::floor(range_f.start() + 0.5f),
548 std::floor(range_f.end() + 0.5f));
551 TextRunHarfBuzz::TextRunHarfBuzz()
552 : width(0.0f),
553 preceding_run_widths(0.0f),
554 is_rtl(false),
555 level(0),
556 script(USCRIPT_INVALID_CODE),
557 glyph_count(static_cast<size_t>(-1)),
558 font_size(0),
559 baseline_offset(0),
560 baseline_type(0),
561 font_style(0),
562 strike(false),
563 diagonal_strike(false),
564 underline(false) {
567 TextRunHarfBuzz::~TextRunHarfBuzz() {}
569 Range TextRunHarfBuzz::CharRangeToGlyphRange(const Range& char_range) const {
570 DCHECK(range.Contains(char_range));
571 DCHECK(!char_range.is_reversed());
572 DCHECK(!char_range.is_empty());
574 Range start_glyphs;
575 Range end_glyphs;
576 Range temp_range;
577 GetClusterAt(char_range.start(), &temp_range, &start_glyphs);
578 GetClusterAt(char_range.end() - 1, &temp_range, &end_glyphs);
580 return is_rtl ? Range(end_glyphs.start(), start_glyphs.end()) :
581 Range(start_glyphs.start(), end_glyphs.end());
584 size_t TextRunHarfBuzz::CountMissingGlyphs() const {
585 static const int kMissingGlyphId = 0;
586 size_t missing = 0;
587 for (size_t i = 0; i < glyph_count; ++i)
588 missing += (glyphs[i] == kMissingGlyphId) ? 1 : 0;
589 return missing;
592 void TextRunHarfBuzz::GetClusterAt(size_t pos,
593 Range* chars,
594 Range* glyphs) const {
595 DCHECK(range.Contains(Range(pos, pos + 1)));
596 DCHECK(chars);
597 DCHECK(glyphs);
599 if (glyph_count == 0) {
600 *chars = range;
601 *glyphs = Range();
602 return;
605 if (is_rtl) {
606 GetClusterAtImpl(pos, range, glyph_to_char.rbegin(), glyph_to_char.rend(),
607 true, chars, glyphs);
608 return;
611 GetClusterAtImpl(pos, range, glyph_to_char.begin(), glyph_to_char.end(),
612 false, chars, glyphs);
615 RangeF TextRunHarfBuzz::GetGraphemeBounds(
616 base::i18n::BreakIterator* grapheme_iterator,
617 size_t text_index) {
618 DCHECK_LT(text_index, range.end());
619 if (glyph_count == 0)
620 return RangeF(preceding_run_widths, preceding_run_widths + width);
622 Range chars;
623 Range glyphs;
624 GetClusterAt(text_index, &chars, &glyphs);
625 const float cluster_begin_x = positions[glyphs.start()].x();
626 const float cluster_end_x = glyphs.end() < glyph_count ?
627 positions[glyphs.end()].x() : SkFloatToScalar(width);
629 // A cluster consists of a number of code points and corresponds to a number
630 // of glyphs that should be drawn together. A cluster can contain multiple
631 // graphemes. In order to place the cursor at a grapheme boundary inside the
632 // cluster, we simply divide the cluster width by the number of graphemes.
633 if (chars.length() > 1 && grapheme_iterator) {
634 int before = 0;
635 int total = 0;
636 for (size_t i = chars.start(); i < chars.end(); ++i) {
637 if (grapheme_iterator->IsGraphemeBoundary(i)) {
638 if (i < text_index)
639 ++before;
640 ++total;
643 DCHECK_GT(total, 0);
644 if (total > 1) {
645 if (is_rtl)
646 before = total - before - 1;
647 DCHECK_GE(before, 0);
648 DCHECK_LT(before, total);
649 const int cluster_width = cluster_end_x - cluster_begin_x;
650 const int grapheme_begin_x = cluster_begin_x + static_cast<int>(0.5f +
651 cluster_width * before / static_cast<float>(total));
652 const int grapheme_end_x = cluster_begin_x + static_cast<int>(0.5f +
653 cluster_width * (before + 1) / static_cast<float>(total));
654 return RangeF(preceding_run_widths + grapheme_begin_x,
655 preceding_run_widths + grapheme_end_x);
659 return RangeF(preceding_run_widths + cluster_begin_x,
660 preceding_run_widths + cluster_end_x);
663 SkScalar TextRunHarfBuzz::GetGlyphWidthForCharRange(
664 const Range& char_range) const {
665 if (char_range.is_empty())
666 return 0;
668 DCHECK(range.Contains(char_range));
669 Range glyph_range = CharRangeToGlyphRange(char_range);
670 return ((glyph_range.end() == glyph_count)
671 ? SkFloatToScalar(width)
672 : positions[glyph_range.end()].x()) -
673 positions[glyph_range.start()].x();
676 TextRunList::TextRunList() : width_(0.0f) {}
678 TextRunList::~TextRunList() {}
680 void TextRunList::Reset() {
681 runs_.clear();
682 width_ = 0.0f;
685 void TextRunList::InitIndexMap() {
686 if (runs_.size() == 1) {
687 visual_to_logical_ = logical_to_visual_ = std::vector<int32_t>(1, 0);
688 return;
690 const size_t num_runs = runs_.size();
691 std::vector<UBiDiLevel> levels(num_runs);
692 for (size_t i = 0; i < num_runs; ++i)
693 levels[i] = runs_[i]->level;
694 visual_to_logical_.resize(num_runs);
695 ubidi_reorderVisual(&levels[0], num_runs, &visual_to_logical_[0]);
696 logical_to_visual_.resize(num_runs);
697 ubidi_reorderLogical(&levels[0], num_runs, &logical_to_visual_[0]);
700 void TextRunList::ComputePrecedingRunWidths() {
701 // Precalculate run width information.
702 width_ = 0.0f;
703 for (size_t i = 0; i < runs_.size(); ++i) {
704 TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
705 run->preceding_run_widths = width_;
706 width_ += run->width;
710 size_t TextRunList::GetRunIndexAt(size_t position) const {
711 for (size_t i = 0; i < runs_.size(); ++i) {
712 if (runs_[i]->range.start() <= position && runs_[i]->range.end() > position)
713 return i;
715 return runs_.size();
718 } // namespace internal
720 RenderTextHarfBuzz::RenderTextHarfBuzz()
721 : RenderText(),
722 update_layout_run_list_(false),
723 update_display_run_list_(false),
724 update_grapheme_iterator_(false),
725 update_display_text_(false),
726 glyph_width_for_test_(0u) {
727 set_truncate_length(kMaxTextLength);
730 RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
732 scoped_ptr<RenderText> RenderTextHarfBuzz::CreateInstanceOfSameType() const {
733 return make_scoped_ptr(new RenderTextHarfBuzz);
736 bool RenderTextHarfBuzz::MultilineSupported() const {
737 return true;
740 const base::string16& RenderTextHarfBuzz::GetDisplayText() {
741 // TODO(oshima): Consider supporting eliding multi-line text.
742 // This requires max_line support first.
743 if (multiline() ||
744 elide_behavior() == NO_ELIDE ||
745 elide_behavior() == FADE_TAIL) {
746 // Call UpdateDisplayText to clear |display_text_| and |text_elided_|
747 // on the RenderText class.
748 UpdateDisplayText(0);
749 update_display_text_ = false;
750 display_run_list_.reset();
751 return layout_text();
754 EnsureLayoutRunList();
755 DCHECK(!update_display_text_);
756 return text_elided() ? display_text() : layout_text();
759 Size RenderTextHarfBuzz::GetStringSize() {
760 const SizeF size_f = GetStringSizeF();
761 return Size(std::ceil(size_f.width()), size_f.height());
764 SizeF RenderTextHarfBuzz::GetStringSizeF() {
765 EnsureLayout();
766 return total_size_;
769 SelectionModel RenderTextHarfBuzz::FindCursorPosition(const Point& point) {
770 EnsureLayout();
772 int x = ToTextPoint(point).x();
773 float offset = 0;
774 size_t run_index = GetRunContainingXCoord(x, &offset);
776 internal::TextRunList* run_list = GetRunList();
777 if (run_index >= run_list->size())
778 return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT);
779 const internal::TextRunHarfBuzz& run = *run_list->runs()[run_index];
780 for (size_t i = 0; i < run.glyph_count; ++i) {
781 const SkScalar end =
782 i + 1 == run.glyph_count ? run.width : run.positions[i + 1].x();
783 const SkScalar middle = (end + run.positions[i].x()) / 2;
785 if (offset < middle) {
786 return SelectionModel(DisplayIndexToTextIndex(
787 run.glyph_to_char[i] + (run.is_rtl ? 1 : 0)),
788 (run.is_rtl ? CURSOR_BACKWARD : CURSOR_FORWARD));
790 if (offset < end) {
791 return SelectionModel(DisplayIndexToTextIndex(
792 run.glyph_to_char[i] + (run.is_rtl ? 0 : 1)),
793 (run.is_rtl ? CURSOR_FORWARD : CURSOR_BACKWARD));
796 return EdgeSelectionModel(CURSOR_RIGHT);
799 std::vector<RenderText::FontSpan> RenderTextHarfBuzz::GetFontSpansForTesting() {
800 EnsureLayout();
802 internal::TextRunList* run_list = GetRunList();
803 std::vector<RenderText::FontSpan> spans;
804 for (auto* run : run_list->runs()) {
805 SkString family_name;
806 run->skia_face->getFamilyName(&family_name);
807 Font font(family_name.c_str(), run->font_size);
808 spans.push_back(RenderText::FontSpan(
809 font,
810 Range(DisplayIndexToTextIndex(run->range.start()),
811 DisplayIndexToTextIndex(run->range.end()))));
814 return spans;
817 Range RenderTextHarfBuzz::GetGlyphBounds(size_t index) {
818 EnsureLayout();
819 const size_t run_index =
820 GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD));
821 internal::TextRunList* run_list = GetRunList();
822 // Return edge bounds if the index is invalid or beyond the layout text size.
823 if (run_index >= run_list->size())
824 return Range(GetStringSize().width());
825 const size_t layout_index = TextIndexToDisplayIndex(index);
826 internal::TextRunHarfBuzz* run = run_list->runs()[run_index];
827 RangeF bounds =
828 run->GetGraphemeBounds(GetGraphemeIterator(), layout_index);
829 // If cursor is enabled, extend the last glyph up to the rightmost cursor
830 // position since clients expect them to be contiguous.
831 if (cursor_enabled() && run_index == run_list->size() - 1 &&
832 index == (run->is_rtl ? run->range.start() : run->range.end() - 1))
833 bounds.set_end(std::ceil(bounds.end()));
834 return RoundRangeF(run->is_rtl ?
835 RangeF(bounds.end(), bounds.start()) : bounds);
838 int RenderTextHarfBuzz::GetDisplayTextBaseline() {
839 EnsureLayout();
840 return lines()[0].baseline;
843 SelectionModel RenderTextHarfBuzz::AdjacentCharSelectionModel(
844 const SelectionModel& selection,
845 VisualCursorDirection direction) {
846 DCHECK(!update_display_run_list_);
848 internal::TextRunList* run_list = GetRunList();
849 internal::TextRunHarfBuzz* run;
851 size_t run_index = GetRunContainingCaret(selection);
852 if (run_index >= run_list->size()) {
853 // The cursor is not in any run: we're at the visual and logical edge.
854 SelectionModel edge = EdgeSelectionModel(direction);
855 if (edge.caret_pos() == selection.caret_pos())
856 return edge;
857 int visual_index = (direction == CURSOR_RIGHT) ? 0 : run_list->size() - 1;
858 run = run_list->runs()[run_list->visual_to_logical(visual_index)];
859 } else {
860 // If the cursor is moving within the current run, just move it by one
861 // grapheme in the appropriate direction.
862 run = run_list->runs()[run_index];
863 size_t caret = selection.caret_pos();
864 bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
865 if (forward_motion) {
866 if (caret < DisplayIndexToTextIndex(run->range.end())) {
867 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
868 return SelectionModel(caret, CURSOR_BACKWARD);
870 } else {
871 if (caret > DisplayIndexToTextIndex(run->range.start())) {
872 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
873 return SelectionModel(caret, CURSOR_FORWARD);
876 // The cursor is at the edge of a run; move to the visually adjacent run.
877 int visual_index = run_list->logical_to_visual(run_index);
878 visual_index += (direction == CURSOR_LEFT) ? -1 : 1;
879 if (visual_index < 0 || visual_index >= static_cast<int>(run_list->size()))
880 return EdgeSelectionModel(direction);
881 run = run_list->runs()[run_list->visual_to_logical(visual_index)];
883 bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
884 return forward_motion ? FirstSelectionModelInsideRun(run) :
885 LastSelectionModelInsideRun(run);
888 SelectionModel RenderTextHarfBuzz::AdjacentWordSelectionModel(
889 const SelectionModel& selection,
890 VisualCursorDirection direction) {
891 if (obscured())
892 return EdgeSelectionModel(direction);
894 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
895 bool success = iter.Init();
896 DCHECK(success);
897 if (!success)
898 return selection;
900 // Match OS specific word break behavior.
901 #if defined(OS_WIN)
902 size_t pos;
903 if (direction == CURSOR_RIGHT) {
904 pos = std::min(selection.caret_pos() + 1, text().length());
905 while (iter.Advance()) {
906 pos = iter.pos();
907 if (iter.IsWord() && pos > selection.caret_pos())
908 break;
910 } else { // direction == CURSOR_LEFT
911 // Notes: We always iterate words from the beginning.
912 // This is probably fast enough for our usage, but we may
913 // want to modify WordIterator so that it can start from the
914 // middle of string and advance backwards.
915 pos = std::max<int>(selection.caret_pos() - 1, 0);
916 while (iter.Advance()) {
917 if (iter.IsWord()) {
918 size_t begin = iter.pos() - iter.GetString().length();
919 if (begin == selection.caret_pos()) {
920 // The cursor is at the beginning of a word.
921 // Move to previous word.
922 break;
923 } else if (iter.pos() >= selection.caret_pos()) {
924 // The cursor is in the middle or at the end of a word.
925 // Move to the top of current word.
926 pos = begin;
927 break;
929 pos = iter.pos() - iter.GetString().length();
933 return SelectionModel(pos, CURSOR_FORWARD);
934 #else
935 internal::TextRunList* run_list = GetRunList();
936 SelectionModel cur(selection);
937 for (;;) {
938 cur = AdjacentCharSelectionModel(cur, direction);
939 size_t run = GetRunContainingCaret(cur);
940 if (run == run_list->size())
941 break;
942 const bool is_forward =
943 run_list->runs()[run]->is_rtl == (direction == CURSOR_LEFT);
944 size_t cursor = cur.caret_pos();
945 if (is_forward ? iter.IsEndOfWord(cursor) : iter.IsStartOfWord(cursor))
946 break;
948 return cur;
949 #endif
952 std::vector<Rect> RenderTextHarfBuzz::GetSubstringBounds(const Range& range) {
953 DCHECK(!update_display_run_list_);
954 DCHECK(Range(0, text().length()).Contains(range));
955 Range layout_range(TextIndexToDisplayIndex(range.start()),
956 TextIndexToDisplayIndex(range.end()));
957 DCHECK(Range(0, GetDisplayText().length()).Contains(layout_range));
959 std::vector<Rect> rects;
960 if (layout_range.is_empty())
961 return rects;
962 std::vector<Range> bounds;
964 internal::TextRunList* run_list = GetRunList();
966 // Add a Range for each run/selection intersection.
967 for (size_t i = 0; i < run_list->size(); ++i) {
968 internal::TextRunHarfBuzz* run =
969 run_list->runs()[run_list->visual_to_logical(i)];
970 Range intersection = run->range.Intersect(layout_range);
971 if (!intersection.IsValid())
972 continue;
973 DCHECK(!intersection.is_reversed());
974 const Range leftmost_character_x = RoundRangeF(run->GetGraphemeBounds(
975 GetGraphemeIterator(),
976 run->is_rtl ? intersection.end() - 1 : intersection.start()));
977 const Range rightmost_character_x = RoundRangeF(run->GetGraphemeBounds(
978 GetGraphemeIterator(),
979 run->is_rtl ? intersection.start() : intersection.end() - 1));
980 Range range_x(leftmost_character_x.start(), rightmost_character_x.end());
981 DCHECK(!range_x.is_reversed());
982 if (range_x.is_empty())
983 continue;
985 // Union this with the last range if they're adjacent.
986 DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin());
987 if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) {
988 range_x = Range(bounds.back().GetMin(), range_x.GetMax());
989 bounds.pop_back();
991 bounds.push_back(range_x);
993 for (Range& bound : bounds) {
994 std::vector<Rect> current_rects = TextBoundsToViewBounds(bound);
995 rects.insert(rects.end(), current_rects.begin(), current_rects.end());
997 return rects;
1000 size_t RenderTextHarfBuzz::TextIndexToDisplayIndex(size_t index) {
1001 return TextIndexToGivenTextIndex(GetDisplayText(), index);
1004 size_t RenderTextHarfBuzz::DisplayIndexToTextIndex(size_t index) {
1005 if (!obscured())
1006 return index;
1007 const size_t text_index = UTF16OffsetToIndex(text(), 0, index);
1008 DCHECK_LE(text_index, text().length());
1009 return text_index;
1012 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index) {
1013 if (index == 0 || index == text().length())
1014 return true;
1015 if (!IsValidLogicalIndex(index))
1016 return false;
1017 base::i18n::BreakIterator* grapheme_iterator = GetGraphemeIterator();
1018 return !grapheme_iterator || grapheme_iterator->IsGraphemeBoundary(index);
1021 void RenderTextHarfBuzz::OnLayoutTextAttributeChanged(bool text_changed) {
1022 update_layout_run_list_ = true;
1023 OnDisplayTextAttributeChanged();
1026 void RenderTextHarfBuzz::OnDisplayTextAttributeChanged() {
1027 update_display_text_ = true;
1028 update_grapheme_iterator_ = true;
1031 void RenderTextHarfBuzz::EnsureLayout() {
1032 EnsureLayoutRunList();
1034 if (update_display_run_list_) {
1035 DCHECK(text_elided());
1036 const base::string16& display_text = GetDisplayText();
1037 display_run_list_.reset(new internal::TextRunList);
1039 if (!display_text.empty()) {
1040 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayout1");
1042 ItemizeTextToRuns(display_text, display_run_list_.get());
1044 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1045 // fixed.
1046 tracked_objects::ScopedTracker tracking_profile(
1047 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 1"));
1048 ShapeRunList(display_text, display_run_list_.get());
1050 update_display_run_list_ = false;
1052 std::vector<internal::Line> empty_lines;
1053 set_lines(&empty_lines);
1056 if (lines().empty()) {
1057 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1058 // fixed.
1059 scoped_ptr<tracked_objects::ScopedTracker> tracking_profile(
1060 new tracked_objects::ScopedTracker(
1061 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 HarfBuzzLineBreaker")));
1063 internal::TextRunList* run_list = GetRunList();
1064 HarfBuzzLineBreaker line_breaker(
1065 display_rect().width(), font_list().GetBaseline(),
1066 std::max(font_list().GetHeight(), min_line_height()),
1067 word_wrap_behavior(), GetDisplayText(),
1068 multiline() ? &GetLineBreaks() : nullptr, *run_list);
1070 tracking_profile.reset();
1072 if (multiline())
1073 line_breaker.ConstructMultiLines();
1074 else
1075 line_breaker.ConstructSingleLine();
1076 std::vector<internal::Line> lines;
1077 line_breaker.FinalizeLines(&lines, &total_size_);
1078 set_lines(&lines);
1082 void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) {
1083 internal::SkiaTextRenderer renderer(canvas);
1084 DrawVisualTextInternal(&renderer);
1087 void RenderTextHarfBuzz::DrawVisualTextInternal(
1088 internal::SkiaTextRenderer* renderer) {
1089 DCHECK(!update_layout_run_list_);
1090 DCHECK(!update_display_run_list_);
1091 DCHECK(!update_display_text_);
1092 if (lines().empty())
1093 return;
1095 ApplyFadeEffects(renderer);
1096 ApplyTextShadows(renderer);
1097 ApplyCompositionAndSelectionStyles();
1099 internal::TextRunList* run_list = GetRunList();
1100 for (size_t i = 0; i < lines().size(); ++i) {
1101 const internal::Line& line = lines()[i];
1102 const Vector2d origin = GetLineOffset(i) + Vector2d(0, line.baseline);
1103 SkScalar preceding_segment_widths = 0;
1104 for (const internal::LineSegment& segment : line.segments) {
1105 const internal::TextRunHarfBuzz& run = *run_list->runs()[segment.run];
1106 renderer->SetTypeface(run.skia_face.get());
1107 renderer->SetTextSize(SkIntToScalar(run.font_size));
1108 renderer->SetFontRenderParams(run.render_params,
1109 subpixel_rendering_suppressed());
1110 Range glyphs_range = run.CharRangeToGlyphRange(segment.char_range);
1111 scoped_ptr<SkPoint[]> positions(new SkPoint[glyphs_range.length()]);
1112 SkScalar offset_x = preceding_segment_widths -
1113 ((glyphs_range.GetMin() != 0)
1114 ? run.positions[glyphs_range.GetMin()].x()
1115 : 0);
1116 for (size_t j = 0; j < glyphs_range.length(); ++j) {
1117 positions[j] = run.positions[(glyphs_range.is_reversed()) ?
1118 (glyphs_range.start() - j) :
1119 (glyphs_range.start() + j)];
1120 positions[j].offset(SkIntToScalar(origin.x()) + offset_x,
1121 SkIntToScalar(origin.y() + run.baseline_offset));
1123 for (BreakList<SkColor>::const_iterator it =
1124 colors().GetBreak(segment.char_range.start());
1125 it != colors().breaks().end() &&
1126 it->first < segment.char_range.end();
1127 ++it) {
1128 const Range intersection =
1129 colors().GetRange(it).Intersect(segment.char_range);
1130 const Range colored_glyphs = run.CharRangeToGlyphRange(intersection);
1131 // The range may be empty if a portion of a multi-character grapheme is
1132 // selected, yielding two colors for a single glyph. For now, this just
1133 // paints the glyph with a single style, but it should paint it twice,
1134 // clipped according to selection bounds. See http://crbug.com/366786
1135 if (colored_glyphs.is_empty())
1136 continue;
1138 renderer->SetForegroundColor(it->second);
1139 renderer->DrawPosText(
1140 &positions[colored_glyphs.start() - glyphs_range.start()],
1141 &run.glyphs[colored_glyphs.start()], colored_glyphs.length());
1142 int start_x = SkScalarRoundToInt(
1143 positions[colored_glyphs.start() - glyphs_range.start()].x());
1144 int end_x = SkScalarRoundToInt(
1145 (colored_glyphs.end() == glyphs_range.end())
1146 ? (SkFloatToScalar(segment.width) + preceding_segment_widths +
1147 SkIntToScalar(origin.x()))
1148 : positions[colored_glyphs.end() - glyphs_range.start()].x());
1149 renderer->DrawDecorations(start_x, origin.y(), end_x - start_x,
1150 run.underline, run.strike,
1151 run.diagonal_strike);
1153 preceding_segment_widths += SkFloatToScalar(segment.width);
1157 renderer->EndDiagonalStrike();
1159 UndoCompositionAndSelectionStyles();
1162 size_t RenderTextHarfBuzz::GetRunContainingCaret(
1163 const SelectionModel& caret) {
1164 DCHECK(!update_display_run_list_);
1165 size_t layout_position = TextIndexToDisplayIndex(caret.caret_pos());
1166 LogicalCursorDirection affinity = caret.caret_affinity();
1167 internal::TextRunList* run_list = GetRunList();
1168 for (size_t i = 0; i < run_list->size(); ++i) {
1169 internal::TextRunHarfBuzz* run = run_list->runs()[i];
1170 if (RangeContainsCaret(run->range, layout_position, affinity))
1171 return i;
1173 return run_list->size();
1176 size_t RenderTextHarfBuzz::GetRunContainingXCoord(float x,
1177 float* offset) const {
1178 DCHECK(!update_display_run_list_);
1179 const internal::TextRunList* run_list = GetRunList();
1180 if (x < 0)
1181 return run_list->size();
1182 // Find the text run containing the argument point (assumed already offset).
1183 float current_x = 0;
1184 for (size_t i = 0; i < run_list->size(); ++i) {
1185 size_t run = run_list->visual_to_logical(i);
1186 current_x += run_list->runs()[run]->width;
1187 if (x < current_x) {
1188 *offset = x - (current_x - run_list->runs()[run]->width);
1189 return run;
1192 return run_list->size();
1195 SelectionModel RenderTextHarfBuzz::FirstSelectionModelInsideRun(
1196 const internal::TextRunHarfBuzz* run) {
1197 size_t position = DisplayIndexToTextIndex(run->range.start());
1198 position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD);
1199 return SelectionModel(position, CURSOR_BACKWARD);
1202 SelectionModel RenderTextHarfBuzz::LastSelectionModelInsideRun(
1203 const internal::TextRunHarfBuzz* run) {
1204 size_t position = DisplayIndexToTextIndex(run->range.end());
1205 position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD);
1206 return SelectionModel(position, CURSOR_FORWARD);
1209 void RenderTextHarfBuzz::ItemizeTextToRuns(
1210 const base::string16& text,
1211 internal::TextRunList* run_list_out) {
1212 DCHECK_NE(0U, text.length());
1214 // If ICU fails to itemize the text, we create a run that spans the entire
1215 // text. This is needed because leaving the runs set empty causes some clients
1216 // to misbehave since they expect non-zero text metrics from a non-empty text.
1217 base::i18n::BiDiLineIterator bidi_iterator;
1218 if (!bidi_iterator.Open(text, GetTextDirection(text))) {
1219 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
1220 run->range = Range(0, text.length());
1221 run_list_out->add(run);
1222 run_list_out->InitIndexMap();
1223 return;
1226 // Temporarily apply composition underlines and selection colors.
1227 ApplyCompositionAndSelectionStyles();
1229 // Build the run list from the script items and ranged styles and baselines.
1230 // Use an empty color BreakList to avoid breaking runs at color boundaries.
1231 BreakList<SkColor> empty_colors;
1232 empty_colors.SetMax(text.length());
1233 DCHECK_LE(text.size(), baselines().max());
1234 for (const BreakList<bool>& style : styles())
1235 DCHECK_LE(text.size(), style.max());
1236 internal::StyleIterator style(empty_colors, baselines(), styles());
1238 for (size_t run_break = 0; run_break < text.length();) {
1239 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
1240 run->range.set_start(run_break);
1241 run->font_style = (style.style(BOLD) ? Font::BOLD : 0) |
1242 (style.style(ITALIC) ? Font::ITALIC : 0);
1243 run->baseline_type = style.baseline();
1244 run->strike = style.style(STRIKE);
1245 run->diagonal_strike = style.style(DIAGONAL_STRIKE);
1246 run->underline = style.style(UNDERLINE);
1247 int32 script_item_break = 0;
1248 bidi_iterator.GetLogicalRun(run_break, &script_item_break, &run->level);
1249 // Odd BiDi embedding levels correspond to RTL runs.
1250 run->is_rtl = (run->level % 2) == 1;
1251 // Find the length and script of this script run.
1252 script_item_break = ScriptInterval(text, run_break,
1253 script_item_break - run_break, &run->script) + run_break;
1255 // Find the next break and advance the iterators as needed.
1256 run_break = std::min(
1257 static_cast<size_t>(script_item_break),
1258 TextIndexToGivenTextIndex(text, style.GetRange().end()));
1260 // Break runs at certain characters that need to be rendered separately to
1261 // prevent either an unusual character from forcing a fallback font on the
1262 // entire run, or brackets from being affected by a fallback font.
1263 // http://crbug.com/278913, http://crbug.com/396776
1264 if (run_break > run->range.start())
1265 run_break = FindRunBreakingCharacter(text, run->range.start(), run_break);
1267 DCHECK(IsValidCodePointIndex(text, run_break));
1268 style.UpdatePosition(DisplayIndexToTextIndex(run_break));
1269 run->range.set_end(run_break);
1271 run_list_out->add(run);
1274 // Undo the temporarily applied composition underlines and selection colors.
1275 UndoCompositionAndSelectionStyles();
1277 run_list_out->InitIndexMap();
1280 bool RenderTextHarfBuzz::CompareFamily(
1281 const base::string16& text,
1282 const std::string& family,
1283 const gfx::FontRenderParams& render_params,
1284 internal::TextRunHarfBuzz* run,
1285 std::string* best_family,
1286 gfx::FontRenderParams* best_render_params,
1287 size_t* best_missing_glyphs) {
1288 if (!ShapeRunWithFont(text, family, render_params, run))
1289 return false;
1291 const size_t missing_glyphs = run->CountMissingGlyphs();
1292 if (missing_glyphs < *best_missing_glyphs) {
1293 *best_family = family;
1294 *best_render_params = render_params;
1295 *best_missing_glyphs = missing_glyphs;
1297 return missing_glyphs == 0;
1300 void RenderTextHarfBuzz::ShapeRunList(const base::string16& text,
1301 internal::TextRunList* run_list) {
1302 for (auto* run : run_list->runs())
1303 ShapeRun(text, run);
1304 run_list->ComputePrecedingRunWidths();
1307 void RenderTextHarfBuzz::ShapeRun(const base::string16& text,
1308 internal::TextRunHarfBuzz* run) {
1309 const Font& primary_font = font_list().GetPrimaryFont();
1310 const std::string primary_family = primary_font.GetFontName();
1311 run->font_size = primary_font.GetFontSize();
1312 run->baseline_offset = 0;
1313 if (run->baseline_type != NORMAL_BASELINE) {
1314 // Calculate a slightly smaller font. The ratio here is somewhat arbitrary.
1315 // Proportions from 5/9 to 5/7 all look pretty good.
1316 const float ratio = 5.0f / 9.0f;
1317 run->font_size = gfx::ToRoundedInt(primary_font.GetFontSize() * ratio);
1318 switch (run->baseline_type) {
1319 case SUPERSCRIPT:
1320 run->baseline_offset =
1321 primary_font.GetCapHeight() - primary_font.GetHeight();
1322 break;
1323 case SUPERIOR:
1324 run->baseline_offset =
1325 gfx::ToRoundedInt(primary_font.GetCapHeight() * ratio) -
1326 primary_font.GetCapHeight();
1327 break;
1328 case SUBSCRIPT:
1329 run->baseline_offset =
1330 primary_font.GetHeight() - primary_font.GetBaseline();
1331 break;
1332 case INFERIOR: // Fall through.
1333 default:
1334 break;
1338 std::string best_family;
1339 FontRenderParams best_render_params;
1340 size_t best_missing_glyphs = std::numeric_limits<size_t>::max();
1342 for (const Font& font : font_list().GetFonts()) {
1343 if (CompareFamily(text, font.GetFontName(), font.GetFontRenderParams(),
1344 run, &best_family, &best_render_params,
1345 &best_missing_glyphs))
1346 return;
1349 #if defined(OS_WIN)
1350 Font uniscribe_font;
1351 std::string uniscribe_family;
1352 const base::char16* run_text = &(text[run->range.start()]);
1353 if (GetUniscribeFallbackFont(primary_font, run_text, run->range.length(),
1354 &uniscribe_font)) {
1355 uniscribe_family = uniscribe_font.GetFontName();
1356 if (CompareFamily(text, uniscribe_family,
1357 uniscribe_font.GetFontRenderParams(), run,
1358 &best_family, &best_render_params, &best_missing_glyphs))
1359 return;
1361 #endif
1363 std::vector<std::string> fallback_families =
1364 GetFallbackFontFamilies(primary_family);
1366 #if defined(OS_WIN)
1367 // Append fonts in the fallback list of the Uniscribe font.
1368 if (!uniscribe_family.empty()) {
1369 std::vector<std::string> uniscribe_fallbacks =
1370 GetFallbackFontFamilies(uniscribe_family);
1371 fallback_families.insert(fallback_families.end(),
1372 uniscribe_fallbacks.begin(), uniscribe_fallbacks.end());
1375 // Add Segoe UI and its associated linked fonts to the fallback font list to
1376 // ensure that the fallback list covers the basic cases.
1377 // http://crbug.com/467459. On some Windows configurations the default font
1378 // could be a raster font like System, which would not give us a reasonable
1379 // fallback font list.
1380 if (!base::LowerCaseEqualsASCII(primary_family, "segoe ui") &&
1381 !base::LowerCaseEqualsASCII(uniscribe_family, "segoe ui")) {
1382 std::vector<std::string> default_fallback_families =
1383 GetFallbackFontFamilies("Segoe UI");
1384 fallback_families.insert(fallback_families.end(),
1385 default_fallback_families.begin(), default_fallback_families.end());
1387 #endif
1389 // Use a set to track the fallback fonts and avoid duplicate entries.
1390 std::set<std::string, CaseInsensitiveCompare> fallback_fonts;
1392 // Try shaping with the fallback fonts.
1393 for (const auto& family : fallback_families) {
1394 if (family == primary_family)
1395 continue;
1396 #if defined(OS_WIN)
1397 if (family == uniscribe_family)
1398 continue;
1399 #endif
1400 if (fallback_fonts.find(family) != fallback_fonts.end())
1401 continue;
1403 fallback_fonts.insert(family);
1405 FontRenderParamsQuery query;
1406 query.families.push_back(family);
1407 query.pixel_size = run->font_size;
1408 query.style = run->font_style;
1409 FontRenderParams fallback_render_params = GetFontRenderParams(query, NULL);
1410 if (CompareFamily(text, family, fallback_render_params, run, &best_family,
1411 &best_render_params, &best_missing_glyphs))
1412 return;
1415 if (!best_family.empty() &&
1416 (best_family == run->family ||
1417 ShapeRunWithFont(text, best_family, best_render_params, run)))
1418 return;
1420 run->glyph_count = 0;
1421 run->width = 0.0f;
1424 bool RenderTextHarfBuzz::ShapeRunWithFont(const base::string16& text,
1425 const std::string& font_family,
1426 const FontRenderParams& params,
1427 internal::TextRunHarfBuzz* run) {
1428 skia::RefPtr<SkTypeface> skia_face =
1429 internal::CreateSkiaTypeface(font_family, run->font_style);
1430 if (skia_face == NULL)
1431 return false;
1432 run->skia_face = skia_face;
1433 run->family = font_family;
1434 run->render_params = params;
1436 hb_font_t* harfbuzz_font = CreateHarfBuzzFont(
1437 run->skia_face.get(), SkIntToScalar(run->font_size), run->render_params,
1438 subpixel_rendering_suppressed());
1440 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
1441 // buffer holds our text, run information to be used by the shaping engine,
1442 // and the resulting glyph data.
1443 hb_buffer_t* buffer = hb_buffer_create();
1444 hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16*>(text.c_str()),
1445 text.length(), run->range.start(), run->range.length());
1446 hb_buffer_set_script(buffer, ICUScriptToHBScript(run->script));
1447 hb_buffer_set_direction(buffer,
1448 run->is_rtl ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
1449 // TODO(ckocagil): Should we determine the actual language?
1450 hb_buffer_set_language(buffer, hb_language_get_default());
1453 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1454 // fixed.
1455 tracked_objects::ScopedTracker tracking_profile(
1456 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 hb_shape()"));
1458 // Shape the text.
1459 hb_shape(harfbuzz_font, buffer, NULL, 0);
1462 // Populate the run fields with the resulting glyph data in the buffer.
1463 unsigned int glyph_count = 0;
1464 hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(buffer, &glyph_count);
1465 run->glyph_count = glyph_count;
1466 hb_glyph_position_t* hb_positions =
1467 hb_buffer_get_glyph_positions(buffer, NULL);
1468 run->glyphs.reset(new uint16[run->glyph_count]);
1469 run->glyph_to_char.resize(run->glyph_count);
1470 run->positions.reset(new SkPoint[run->glyph_count]);
1471 run->width = 0.0f;
1473 for (size_t i = 0; i < run->glyph_count; ++i) {
1474 DCHECK_LE(infos[i].codepoint, std::numeric_limits<uint16>::max());
1475 run->glyphs[i] = static_cast<uint16>(infos[i].codepoint);
1476 run->glyph_to_char[i] = infos[i].cluster;
1477 const SkScalar x_offset = SkFixedToScalar(hb_positions[i].x_offset);
1478 const SkScalar y_offset = SkFixedToScalar(hb_positions[i].y_offset);
1479 run->positions[i].set(run->width + x_offset, -y_offset);
1480 run->width += (glyph_width_for_test_ > 0)
1481 ? glyph_width_for_test_
1482 : SkFixedToFloat(hb_positions[i].x_advance);
1483 // Round run widths if subpixel positioning is off to match native behavior.
1484 if (!run->render_params.subpixel_positioning)
1485 run->width = std::floor(run->width + 0.5f);
1488 hb_buffer_destroy(buffer);
1489 hb_font_destroy(harfbuzz_font);
1490 return true;
1493 void RenderTextHarfBuzz::EnsureLayoutRunList() {
1494 if (update_layout_run_list_) {
1495 layout_run_list_.Reset();
1497 const base::string16& text = layout_text();
1498 if (!text.empty()) {
1499 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayoutRunList");
1500 ItemizeTextToRuns(text, &layout_run_list_);
1502 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1503 // fixed.
1504 tracked_objects::ScopedTracker tracking_profile(
1505 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 2"));
1506 ShapeRunList(text, &layout_run_list_);
1509 std::vector<internal::Line> empty_lines;
1510 set_lines(&empty_lines);
1511 display_run_list_.reset();
1512 update_display_text_ = true;
1513 update_layout_run_list_ = false;
1515 if (update_display_text_) {
1516 UpdateDisplayText(multiline() ? 0 : layout_run_list_.width());
1517 update_display_text_ = false;
1518 update_display_run_list_ = text_elided();
1522 base::i18n::BreakIterator* RenderTextHarfBuzz::GetGraphemeIterator() {
1523 if (update_grapheme_iterator_) {
1524 update_grapheme_iterator_ = false;
1525 grapheme_iterator_.reset(new base::i18n::BreakIterator(
1526 GetDisplayText(),
1527 base::i18n::BreakIterator::BREAK_CHARACTER));
1528 if (!grapheme_iterator_->Init())
1529 grapheme_iterator_.reset();
1531 return grapheme_iterator_.get();
1534 internal::TextRunList* RenderTextHarfBuzz::GetRunList() {
1535 DCHECK(!update_layout_run_list_);
1536 DCHECK(!update_display_run_list_);
1537 return text_elided() ? display_run_list_.get() : &layout_run_list_;
1540 const internal::TextRunList* RenderTextHarfBuzz::GetRunList() const {
1541 return const_cast<RenderTextHarfBuzz*>(this)->GetRunList();
1544 } // namespace gfx