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"
10 #include "base/i18n/bidi_line_iterator.h"
11 #include "base/i18n/break_iterator.h"
12 #include "base/i18n/char_iterator.h"
13 #include "base/profiler/scoped_tracker.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/trace_event/trace_event.h"
17 #include "third_party/harfbuzz-ng/src/hb.h"
18 #include "third_party/icu/source/common/unicode/ubidi.h"
19 #include "third_party/skia/include/core/SkColor.h"
20 #include "third_party/skia/include/core/SkTypeface.h"
21 #include "ui/gfx/canvas.h"
22 #include "ui/gfx/font_fallback.h"
23 #include "ui/gfx/font_render_params.h"
24 #include "ui/gfx/geometry/safe_integer_conversions.h"
25 #include "ui/gfx/harfbuzz_font_skia.h"
26 #include "ui/gfx/range/range_f.h"
27 #include "ui/gfx/utf16_indexing.h"
30 #include "ui/gfx/font_fallback_win.h"
33 using gfx::internal::RoundRangeF
;
39 // Text length limit. Longer strings are slow and not fully tested.
40 const size_t kMaxTextLength
= 10000;
42 // The maximum number of scripts a Unicode character can belong to. This value
43 // is arbitrarily chosen to be a good limit because it is unlikely for a single
44 // character to belong to more scripts.
45 const size_t kMaxScripts
= 5;
47 // Returns true if characters of |block_code| may trigger font fallback.
48 // Dingbats and emoticons can be rendered through the color emoji font file,
49 // therefore it needs to be trigerred as fallbacks. See crbug.com/448909
50 bool IsUnusualBlockCode(UBlockCode block_code
) {
51 return block_code
== UBLOCK_GEOMETRIC_SHAPES
||
52 block_code
== UBLOCK_MISCELLANEOUS_SYMBOLS
||
53 block_code
== UBLOCK_DINGBATS
||
54 block_code
== UBLOCK_EMOTICONS
;
57 bool IsBracket(UChar32 character
) {
58 static const char kBrackets
[] = { '(', ')', '{', '}', '<', '>', };
59 static const char* kBracketsEnd
= kBrackets
+ arraysize(kBrackets
);
60 return std::find(kBrackets
, kBracketsEnd
, character
) != kBracketsEnd
;
63 // Returns the boundary between a special and a regular character. Special
64 // characters are brackets or characters that satisfy |IsUnusualBlockCode|.
65 size_t FindRunBreakingCharacter(const base::string16
& text
,
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')
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();
93 // If the given scripts match, returns the one that isn't USCRIPT_COMMON or
94 // USCRIPT_INHERITED, i.e. the more specific one. Otherwise returns
95 // USCRIPT_INVALID_CODE.
96 UScriptCode
ScriptIntersect(UScriptCode first
, UScriptCode second
) {
97 if (first
== second
||
98 (second
> USCRIPT_INVALID_CODE
&& second
<= USCRIPT_INHERITED
)) {
101 if (first
> USCRIPT_INVALID_CODE
&& first
<= USCRIPT_INHERITED
)
103 return USCRIPT_INVALID_CODE
;
106 // Writes the script and the script extensions of the character with the
107 // Unicode |codepoint|. Returns the number of written scripts.
108 int GetScriptExtensions(UChar32 codepoint
, UScriptCode
* scripts
) {
109 UErrorCode icu_error
= U_ZERO_ERROR
;
110 // ICU documentation incorrectly states that the result of
111 // |uscript_getScriptExtensions| will contain the regular script property.
112 // Write the character's script property to the first element.
113 scripts
[0] = uscript_getScript(codepoint
, &icu_error
);
114 if (U_FAILURE(icu_error
))
116 // Fill the rest of |scripts| with the extensions.
117 int count
= uscript_getScriptExtensions(codepoint
, scripts
+ 1,
118 kMaxScripts
- 1, &icu_error
);
119 if (U_FAILURE(icu_error
))
124 // Intersects the script extensions set of |codepoint| with |result| and writes
125 // to |result|, reading and updating |result_size|.
126 void ScriptSetIntersect(UChar32 codepoint
,
128 size_t* result_size
) {
129 UScriptCode scripts
[kMaxScripts
] = { USCRIPT_INVALID_CODE
};
130 int count
= GetScriptExtensions(codepoint
, scripts
);
134 for (size_t i
= 0; i
< *result_size
; ++i
) {
135 for (int j
= 0; j
< count
; ++j
) {
136 UScriptCode intersection
= ScriptIntersect(result
[i
], scripts
[j
]);
137 if (intersection
!= USCRIPT_INVALID_CODE
) {
138 result
[out_size
++] = intersection
;
144 *result_size
= out_size
;
147 // Find the longest sequence of characters from 0 and up to |length| that
148 // have at least one common UScriptCode value. Writes the common script value to
149 // |script| and returns the length of the sequence. Takes the characters' script
150 // extensions into account. http://www.unicode.org/reports/tr24/#ScriptX
152 // Consider 3 characters with the script values {Kana}, {Hira, Kana}, {Kana}.
153 // Without script extensions only the first script in each set would be taken
154 // into account, resulting in 3 runs where 1 would be enough.
155 // TODO(ckocagil): Write a unit test for the case above.
156 int ScriptInterval(const base::string16
& text
,
159 UScriptCode
* script
) {
160 DCHECK_GT(length
, 0U);
162 UScriptCode scripts
[kMaxScripts
] = { USCRIPT_INVALID_CODE
};
164 base::i18n::UTF16CharIterator
char_iterator(text
.c_str() + start
, length
);
165 size_t scripts_size
= GetScriptExtensions(char_iterator
.get(), scripts
);
166 *script
= scripts
[0];
168 while (char_iterator
.Advance()) {
169 ScriptSetIntersect(char_iterator
.get(), scripts
, &scripts_size
);
170 if (scripts_size
== 0U)
171 return char_iterator
.array_pos();
172 *script
= scripts
[0];
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
,
191 Iterator elements_begin
,
192 Iterator elements_end
,
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
);
204 reversed
? elements_end
- element
: element
- elements_begin
);
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
{
223 HarfBuzzLineBreaker(size_t max_width
,
227 WordWrapBehavior word_wrap_behavior
,
228 const base::string16
& text
,
229 const BreakList
<size_t>* words
,
230 const internal::TextRunList
& run_list
)
231 : max_width_((max_width
== 0) ? SK_ScalarMax
: SkIntToScalar(max_width
)),
232 min_baseline_(min_baseline
),
233 min_height_(min_height
),
234 multiline_(multiline
),
235 word_wrap_behavior_(word_wrap_behavior
),
243 DCHECK_EQ(multiline_
, (words_
!= nullptr));
247 // Breaks the run at given |run_index| into Line structs.
248 void AddRun(int run_index
) {
249 const internal::TextRunHarfBuzz
* run
= run_list_
.runs()[run_index
];
250 base::char16 first_char
= text_
[run
->range
.start()];
251 if (multiline_
&& first_char
== '\n') {
253 } else if (multiline_
&& (line_x_
+ SkFloatToScalar(run
->width
)) >
257 AddSegment(run_index
, run
->range
, run
->width
);
261 // Finishes line breaking and outputs the results. Can be called at most once.
262 void Finalize(std::vector
<internal::Line
>* lines
, SizeF
* size
) {
263 DCHECK(!lines_
.empty());
264 // Add an empty line to finish the line size calculation and remove it.
272 // A (line index, segment index) pair that specifies a segment in |lines_|.
273 typedef std::pair
<size_t, size_t> SegmentHandle
;
275 internal::LineSegment
* SegmentFromHandle(const SegmentHandle
& handle
) {
276 return &lines_
[handle
.first
].segments
[handle
.second
];
279 // Breaks a run into segments that fit in the last line in |lines_| and adds
280 // them. Adds a new Line to the back of |lines_| whenever a new segment can't
281 // be added without the Line's width exceeding |max_width_|.
282 void BreakRun(int run_index
) {
283 const internal::TextRunHarfBuzz
& run
= *(run_list_
.runs()[run_index
]);
285 size_t next_char
= run
.range
.start();
287 // Break the run until it fits the current line.
288 while (next_char
< run
.range
.end()) {
289 const size_t current_char
= next_char
;
290 size_t end_char
= next_char
;
291 const bool skip_line
=
292 BreakRunAtWidth(run
, current_char
, &width
, &end_char
, &next_char
);
293 AddSegment(run_index
, Range(current_char
, end_char
),
294 SkScalarToFloat(width
));
300 // Starting from |start_char|, finds a suitable line break position at or
301 // before available width using word break. If the current position is at the
302 // beginning of a line, this function will not roll back to |start_char| and
303 // |*next_char| will be greater than |start_char| (to avoid constructing empty
304 // lines). It stores the end of the segment range to |end_char|, which can be
305 // smaller than |*next_char| for certain word wrapping behavior.
306 // Returns whether to skip the line before |*next_char|.
307 // TODO(ckocagil): We might have to reshape after breaking at ligatures.
308 // See whether resolving the TODO above resolves this too.
309 // TODO(ckocagil): Do not reserve width for whitespace at the end of lines.
310 bool BreakRunAtWidth(const internal::TextRunHarfBuzz
& run
,
316 DCHECK(run
.range
.Contains(Range(start_char
, start_char
+ 1)));
317 SkScalar available_width
= max_width_
- line_x_
;
318 BreakList
<size_t>::const_iterator word
= words_
->GetBreak(start_char
);
319 BreakList
<size_t>::const_iterator next_word
= word
+ 1;
320 // Width from |std::max(word->first, start_char)| to the current character.
321 SkScalar word_width
= 0;
325 SkScalar truncated_width
= 0;
326 for (size_t i
= start_char
; i
< run
.range
.end(); i
+= char_range
.length()) {
327 // |word| holds the word boundary at or before |i|, and |next_word| holds
328 // the word boundary right after |i|. Advance both |word| and |next_word|
329 // when |i| reaches |next_word|.
330 if (next_word
!= words_
->breaks().end() && i
>= next_word
->first
) {
331 if (*width
> available_width
) {
332 DCHECK_NE(WRAP_LONG_WORDS
, word_wrap_behavior_
);
334 if (word_wrap_behavior_
!= TRUNCATE_LONG_WORDS
)
335 *end_char
= *next_char
;
337 *width
= truncated_width
;
345 run
.GetClusterAt(i
, &char_range
, &glyph_range
);
346 DCHECK_LT(0U, char_range
.length());
348 SkScalar char_width
= ((glyph_range
.end() >= run
.glyph_count
)
349 ? SkFloatToScalar(run
.width
)
350 : run
.positions
[glyph_range
.end()].x()) -
351 run
.positions
[glyph_range
.start()].x();
353 *width
+= char_width
;
354 word_width
+= char_width
;
356 // TODO(mukai): implement ELIDE_LONG_WORDS.
357 if (*width
> available_width
) {
358 if (line_x_
!= 0 || word_width
< *width
) {
359 // Roll back one word.
360 *width
-= word_width
;
361 *next_char
= std::max(word
->first
, start_char
);
362 *end_char
= *next_char
;
364 } else if (word_wrap_behavior_
== WRAP_LONG_WORDS
) {
365 if (char_width
< *width
) {
366 // Roll back one character.
367 *width
-= char_width
;
370 // Continue from the next character.
371 *next_char
= i
+ char_range
.length();
373 *end_char
= *next_char
;
377 *end_char
= char_range
.end();
378 truncated_width
= *width
;
382 if (word_wrap_behavior_
== TRUNCATE_LONG_WORDS
)
383 *width
= truncated_width
;
384 *end_char
= *next_char
= run
.range
.end();
388 // RTL runs are broken in logical order but displayed in visual order. To find
389 // the text-space coordinate (where it would fall in a single-line text)
390 // |x_range| of RTL segments, segment widths are applied in reverse order.
391 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}.
392 void UpdateRTLSegmentRanges() {
393 if (rtl_segments_
.empty())
395 float x
= SegmentFromHandle(rtl_segments_
[0])->x_range
.start();
396 for (size_t i
= rtl_segments_
.size(); i
> 0; --i
) {
397 internal::LineSegment
* segment
= SegmentFromHandle(rtl_segments_
[i
- 1]);
398 const float segment_width
= segment
->width
;
399 segment
->x_range
= Range(x
, x
+ segment_width
);
402 rtl_segments_
.clear();
405 // Finishes the size calculations of the last Line in |lines_|. Adds a new
406 // Line to the back of |lines_|.
408 if (!lines_
.empty()) {
409 internal::Line
* line
= &lines_
.back();
410 std::sort(line
->segments
.begin(), line
->segments
.end(),
411 [this](const internal::LineSegment
& s1
,
412 const internal::LineSegment
& s2
) -> bool {
413 return run_list_
.logical_to_visual(s1
.run
) <
414 run_list_
.logical_to_visual(s2
.run
);
416 line
->size
.set_height(std::max(min_height_
, max_descent_
+ max_ascent_
));
418 std::max(min_baseline_
, SkScalarRoundToInt(max_ascent_
));
419 line
->preceding_heights
= std::ceil(total_size_
.height());
420 total_size_
.set_height(total_size_
.height() + line
->size
.height());
421 total_size_
.set_width(std::max(total_size_
.width(), line
->size
.width()));
426 lines_
.push_back(internal::Line());
429 // Adds a new segment with the given properties to |lines_.back()|.
430 void AddSegment(int run_index
, Range char_range
, float width
) {
431 if (char_range
.is_empty()) {
435 const internal::TextRunHarfBuzz
& run
= *(run_list_
.runs()[run_index
]);
437 internal::LineSegment segment
;
438 segment
.run
= run_index
;
439 segment
.char_range
= char_range
;
440 segment
.x_range
= Range(
441 SkScalarCeilToInt(text_x_
),
442 SkScalarCeilToInt(text_x_
+ SkFloatToScalar(width
)));
443 segment
.width
= width
;
445 internal::Line
* line
= &lines_
.back();
446 line
->segments
.push_back(segment
);
449 paint
.setTypeface(run
.skia_face
.get());
450 paint
.setTextSize(SkIntToScalar(run
.font_size
));
451 paint
.setAntiAlias(run
.render_params
.antialiasing
);
452 SkPaint::FontMetrics metrics
;
453 paint
.getFontMetrics(&metrics
);
455 line
->size
.set_width(line
->size
.width() + width
);
456 // TODO(dschuyler): Account for stylized baselines in string sizing.
457 max_descent_
= std::max(max_descent_
, metrics
.fDescent
);
458 // fAscent is always negative.
459 max_ascent_
= std::max(max_ascent_
, -metrics
.fAscent
);
462 rtl_segments_
.push_back(
463 SegmentHandle(lines_
.size() - 1, line
->segments
.size() - 1));
464 // If this is the last segment of an RTL run, reprocess the text-space x
465 // ranges of all segments from the run.
466 if (char_range
.end() == run
.range
.end())
467 UpdateRTLSegmentRanges();
469 text_x_
+= SkFloatToScalar(width
);
470 line_x_
+= SkFloatToScalar(width
);
473 const SkScalar max_width_
;
474 const int min_baseline_
;
475 const float min_height_
;
476 const bool multiline_
;
477 const WordWrapBehavior word_wrap_behavior_
;
478 const base::string16
& text_
;
479 const BreakList
<size_t>* const words_
;
480 const internal::TextRunList
& run_list_
;
482 // Stores the resulting lines.
483 std::vector
<internal::Line
> lines_
;
485 // Text space and line space x coordinates of the next segment to be added.
492 // Size of the multiline text, not including the currently processed line.
495 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
496 std::vector
<SegmentHandle
> rtl_segments_
;
498 DISALLOW_COPY_AND_ASSIGN(HarfBuzzLineBreaker
);
501 // Function object for case insensitive string comparison.
502 struct CaseInsensitiveCompare
{
503 bool operator() (const std::string
& a
, const std::string
& b
) const {
504 return base::strncasecmp(a
.c_str(), b
.c_str(), b
.length()) < 0;
512 Range
RoundRangeF(const RangeF
& range_f
) {
513 return Range(std::floor(range_f
.start() + 0.5f
),
514 std::floor(range_f
.end() + 0.5f
));
517 TextRunHarfBuzz::TextRunHarfBuzz()
519 preceding_run_widths(0.0f
),
522 script(USCRIPT_INVALID_CODE
),
523 glyph_count(static_cast<size_t>(-1)),
529 diagonal_strike(false),
533 TextRunHarfBuzz::~TextRunHarfBuzz() {}
535 void TextRunHarfBuzz::GetClusterAt(size_t pos
,
537 Range
* glyphs
) const {
538 DCHECK(range
.Contains(Range(pos
, pos
+ 1)));
542 if (glyph_count
== 0) {
549 GetClusterAtImpl(pos
, range
, glyph_to_char
.rbegin(), glyph_to_char
.rend(),
550 true, chars
, glyphs
);
554 GetClusterAtImpl(pos
, range
, glyph_to_char
.begin(), glyph_to_char
.end(),
555 false, chars
, glyphs
);
558 Range
TextRunHarfBuzz::CharRangeToGlyphRange(const Range
& char_range
) const {
559 DCHECK(range
.Contains(char_range
));
560 DCHECK(!char_range
.is_reversed());
561 DCHECK(!char_range
.is_empty());
566 GetClusterAt(char_range
.start(), &temp_range
, &start_glyphs
);
567 GetClusterAt(char_range
.end() - 1, &temp_range
, &end_glyphs
);
569 return is_rtl
? Range(end_glyphs
.start(), start_glyphs
.end()) :
570 Range(start_glyphs
.start(), end_glyphs
.end());
573 size_t TextRunHarfBuzz::CountMissingGlyphs() const {
574 static const int kMissingGlyphId
= 0;
576 for (size_t i
= 0; i
< glyph_count
; ++i
)
577 missing
+= (glyphs
[i
] == kMissingGlyphId
) ? 1 : 0;
581 RangeF
TextRunHarfBuzz::GetGraphemeBounds(
582 base::i18n::BreakIterator
* grapheme_iterator
,
584 DCHECK_LT(text_index
, range
.end());
585 if (glyph_count
== 0)
586 return RangeF(preceding_run_widths
, preceding_run_widths
+ width
);
590 GetClusterAt(text_index
, &chars
, &glyphs
);
591 const float cluster_begin_x
= positions
[glyphs
.start()].x();
592 const float cluster_end_x
= glyphs
.end() < glyph_count
?
593 positions
[glyphs
.end()].x() : SkFloatToScalar(width
);
595 // A cluster consists of a number of code points and corresponds to a number
596 // of glyphs that should be drawn together. A cluster can contain multiple
597 // graphemes. In order to place the cursor at a grapheme boundary inside the
598 // cluster, we simply divide the cluster width by the number of graphemes.
599 if (chars
.length() > 1 && grapheme_iterator
) {
602 for (size_t i
= chars
.start(); i
< chars
.end(); ++i
) {
603 if (grapheme_iterator
->IsGraphemeBoundary(i
)) {
612 before
= total
- before
- 1;
613 DCHECK_GE(before
, 0);
614 DCHECK_LT(before
, total
);
615 const int cluster_width
= cluster_end_x
- cluster_begin_x
;
616 const int grapheme_begin_x
= cluster_begin_x
+ static_cast<int>(0.5f
+
617 cluster_width
* before
/ static_cast<float>(total
));
618 const int grapheme_end_x
= cluster_begin_x
+ static_cast<int>(0.5f
+
619 cluster_width
* (before
+ 1) / static_cast<float>(total
));
620 return RangeF(preceding_run_widths
+ grapheme_begin_x
,
621 preceding_run_widths
+ grapheme_end_x
);
625 return RangeF(preceding_run_widths
+ cluster_begin_x
,
626 preceding_run_widths
+ cluster_end_x
);
629 TextRunList::TextRunList() : width_(0.0f
) {}
631 TextRunList::~TextRunList() {}
633 void TextRunList::Reset() {
638 void TextRunList::InitIndexMap() {
639 if (runs_
.size() == 1) {
640 visual_to_logical_
= logical_to_visual_
= std::vector
<int32_t>(1, 0);
643 const size_t num_runs
= runs_
.size();
644 std::vector
<UBiDiLevel
> levels(num_runs
);
645 for (size_t i
= 0; i
< num_runs
; ++i
)
646 levels
[i
] = runs_
[i
]->level
;
647 visual_to_logical_
.resize(num_runs
);
648 ubidi_reorderVisual(&levels
[0], num_runs
, &visual_to_logical_
[0]);
649 logical_to_visual_
.resize(num_runs
);
650 ubidi_reorderLogical(&levels
[0], num_runs
, &logical_to_visual_
[0]);
653 void TextRunList::ComputePrecedingRunWidths() {
654 // Precalculate run width information.
656 for (size_t i
= 0; i
< runs_
.size(); ++i
) {
657 TextRunHarfBuzz
* run
= runs_
[visual_to_logical_
[i
]];
658 run
->preceding_run_widths
= width_
;
659 width_
+= run
->width
;
663 } // namespace internal
665 RenderTextHarfBuzz::RenderTextHarfBuzz()
667 update_layout_run_list_(false),
668 update_display_run_list_(false),
669 update_grapheme_iterator_(false),
670 update_display_text_(false),
671 glyph_width_for_test_(0u) {
672 set_truncate_length(kMaxTextLength
);
675 RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
677 scoped_ptr
<RenderText
> RenderTextHarfBuzz::CreateInstanceOfSameType() const {
678 return make_scoped_ptr(new RenderTextHarfBuzz
);
681 bool RenderTextHarfBuzz::MultilineSupported() const {
685 const base::string16
& RenderTextHarfBuzz::GetDisplayText() {
686 // TODO(oshima): Consider supporting eliding multi-line text.
687 // This requires max_line support first.
689 elide_behavior() == NO_ELIDE
||
690 elide_behavior() == FADE_TAIL
) {
691 // Call UpdateDisplayText to clear |display_text_| and |text_elided_|
692 // on the RenderText class.
693 UpdateDisplayText(0);
694 update_display_text_
= false;
695 display_run_list_
.reset();
696 return layout_text();
699 EnsureLayoutRunList();
700 DCHECK(!update_display_text_
);
701 return text_elided() ? display_text() : layout_text();
704 Size
RenderTextHarfBuzz::GetStringSize() {
705 const SizeF size_f
= GetStringSizeF();
706 return Size(std::ceil(size_f
.width()), size_f
.height());
709 SizeF
RenderTextHarfBuzz::GetStringSizeF() {
714 SelectionModel
RenderTextHarfBuzz::FindCursorPosition(const Point
& point
) {
717 int x
= ToTextPoint(point
).x();
719 size_t run_index
= GetRunContainingXCoord(x
, &offset
);
721 internal::TextRunList
* run_list
= GetRunList();
722 if (run_index
>= run_list
->size())
723 return EdgeSelectionModel((x
< 0) ? CURSOR_LEFT
: CURSOR_RIGHT
);
724 const internal::TextRunHarfBuzz
& run
= *run_list
->runs()[run_index
];
725 for (size_t i
= 0; i
< run
.glyph_count
; ++i
) {
727 i
+ 1 == run
.glyph_count
? run
.width
: run
.positions
[i
+ 1].x();
728 const SkScalar middle
= (end
+ run
.positions
[i
].x()) / 2;
730 if (offset
< middle
) {
731 return SelectionModel(DisplayIndexToTextIndex(
732 run
.glyph_to_char
[i
] + (run
.is_rtl
? 1 : 0)),
733 (run
.is_rtl
? CURSOR_BACKWARD
: CURSOR_FORWARD
));
736 return SelectionModel(DisplayIndexToTextIndex(
737 run
.glyph_to_char
[i
] + (run
.is_rtl
? 0 : 1)),
738 (run
.is_rtl
? CURSOR_FORWARD
: CURSOR_BACKWARD
));
741 return EdgeSelectionModel(CURSOR_RIGHT
);
744 std::vector
<RenderText::FontSpan
> RenderTextHarfBuzz::GetFontSpansForTesting() {
747 internal::TextRunList
* run_list
= GetRunList();
748 std::vector
<RenderText::FontSpan
> spans
;
749 for (auto* run
: run_list
->runs()) {
750 SkString family_name
;
751 run
->skia_face
->getFamilyName(&family_name
);
752 Font
font(family_name
.c_str(), run
->font_size
);
753 spans
.push_back(RenderText::FontSpan(
755 Range(DisplayIndexToTextIndex(run
->range
.start()),
756 DisplayIndexToTextIndex(run
->range
.end()))));
762 Range
RenderTextHarfBuzz::GetGlyphBounds(size_t index
) {
764 const size_t run_index
=
765 GetRunContainingCaret(SelectionModel(index
, CURSOR_FORWARD
));
766 internal::TextRunList
* run_list
= GetRunList();
767 // Return edge bounds if the index is invalid or beyond the layout text size.
768 if (run_index
>= run_list
->size())
769 return Range(GetStringSize().width());
770 const size_t layout_index
= TextIndexToDisplayIndex(index
);
771 internal::TextRunHarfBuzz
* run
= run_list
->runs()[run_index
];
773 run
->GetGraphemeBounds(GetGraphemeIterator(), layout_index
);
774 // If cursor is enabled, extend the last glyph up to the rightmost cursor
775 // position since clients expect them to be contiguous.
776 if (cursor_enabled() && run_index
== run_list
->size() - 1 &&
777 index
== (run
->is_rtl
? run
->range
.start() : run
->range
.end() - 1))
778 bounds
.set_end(std::ceil(bounds
.end()));
779 return RoundRangeF(run
->is_rtl
?
780 RangeF(bounds
.end(), bounds
.start()) : bounds
);
783 int RenderTextHarfBuzz::GetDisplayTextBaseline() {
785 return lines()[0].baseline
;
788 SelectionModel
RenderTextHarfBuzz::AdjacentCharSelectionModel(
789 const SelectionModel
& selection
,
790 VisualCursorDirection direction
) {
791 DCHECK(!update_display_run_list_
);
793 internal::TextRunList
* run_list
= GetRunList();
794 internal::TextRunHarfBuzz
* run
;
796 size_t run_index
= GetRunContainingCaret(selection
);
797 if (run_index
>= run_list
->size()) {
798 // The cursor is not in any run: we're at the visual and logical edge.
799 SelectionModel edge
= EdgeSelectionModel(direction
);
800 if (edge
.caret_pos() == selection
.caret_pos())
802 int visual_index
= (direction
== CURSOR_RIGHT
) ? 0 : run_list
->size() - 1;
803 run
= run_list
->runs()[run_list
->visual_to_logical(visual_index
)];
805 // If the cursor is moving within the current run, just move it by one
806 // grapheme in the appropriate direction.
807 run
= run_list
->runs()[run_index
];
808 size_t caret
= selection
.caret_pos();
809 bool forward_motion
= run
->is_rtl
== (direction
== CURSOR_LEFT
);
810 if (forward_motion
) {
811 if (caret
< DisplayIndexToTextIndex(run
->range
.end())) {
812 caret
= IndexOfAdjacentGrapheme(caret
, CURSOR_FORWARD
);
813 return SelectionModel(caret
, CURSOR_BACKWARD
);
816 if (caret
> DisplayIndexToTextIndex(run
->range
.start())) {
817 caret
= IndexOfAdjacentGrapheme(caret
, CURSOR_BACKWARD
);
818 return SelectionModel(caret
, CURSOR_FORWARD
);
821 // The cursor is at the edge of a run; move to the visually adjacent run.
822 int visual_index
= run_list
->logical_to_visual(run_index
);
823 visual_index
+= (direction
== CURSOR_LEFT
) ? -1 : 1;
824 if (visual_index
< 0 || visual_index
>= static_cast<int>(run_list
->size()))
825 return EdgeSelectionModel(direction
);
826 run
= run_list
->runs()[run_list
->visual_to_logical(visual_index
)];
828 bool forward_motion
= run
->is_rtl
== (direction
== CURSOR_LEFT
);
829 return forward_motion
? FirstSelectionModelInsideRun(run
) :
830 LastSelectionModelInsideRun(run
);
833 SelectionModel
RenderTextHarfBuzz::AdjacentWordSelectionModel(
834 const SelectionModel
& selection
,
835 VisualCursorDirection direction
) {
837 return EdgeSelectionModel(direction
);
839 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
840 bool success
= iter
.Init();
845 // Match OS specific word break behavior.
848 if (direction
== CURSOR_RIGHT
) {
849 pos
= std::min(selection
.caret_pos() + 1, text().length());
850 while (iter
.Advance()) {
852 if (iter
.IsWord() && pos
> selection
.caret_pos())
855 } else { // direction == CURSOR_LEFT
856 // Notes: We always iterate words from the beginning.
857 // This is probably fast enough for our usage, but we may
858 // want to modify WordIterator so that it can start from the
859 // middle of string and advance backwards.
860 pos
= std::max
<int>(selection
.caret_pos() - 1, 0);
861 while (iter
.Advance()) {
863 size_t begin
= iter
.pos() - iter
.GetString().length();
864 if (begin
== selection
.caret_pos()) {
865 // The cursor is at the beginning of a word.
866 // Move to previous word.
868 } else if (iter
.pos() >= selection
.caret_pos()) {
869 // The cursor is in the middle or at the end of a word.
870 // Move to the top of current word.
874 pos
= iter
.pos() - iter
.GetString().length();
878 return SelectionModel(pos
, CURSOR_FORWARD
);
880 internal::TextRunList
* run_list
= GetRunList();
881 SelectionModel
cur(selection
);
883 cur
= AdjacentCharSelectionModel(cur
, direction
);
884 size_t run
= GetRunContainingCaret(cur
);
885 if (run
== run_list
->size())
887 const bool is_forward
=
888 run_list
->runs()[run
]->is_rtl
== (direction
== CURSOR_LEFT
);
889 size_t cursor
= cur
.caret_pos();
890 if (is_forward
? iter
.IsEndOfWord(cursor
) : iter
.IsStartOfWord(cursor
))
897 std::vector
<Rect
> RenderTextHarfBuzz::GetSubstringBounds(const Range
& range
) {
898 DCHECK(!update_display_run_list_
);
899 DCHECK(Range(0, text().length()).Contains(range
));
900 Range
layout_range(TextIndexToDisplayIndex(range
.start()),
901 TextIndexToDisplayIndex(range
.end()));
902 DCHECK(Range(0, GetDisplayText().length()).Contains(layout_range
));
904 std::vector
<Rect
> rects
;
905 if (layout_range
.is_empty())
907 std::vector
<Range
> bounds
;
909 internal::TextRunList
* run_list
= GetRunList();
911 // Add a Range for each run/selection intersection.
912 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
913 internal::TextRunHarfBuzz
* run
=
914 run_list
->runs()[run_list
->visual_to_logical(i
)];
915 Range intersection
= run
->range
.Intersect(layout_range
);
916 if (!intersection
.IsValid())
918 DCHECK(!intersection
.is_reversed());
919 const Range leftmost_character_x
= RoundRangeF(run
->GetGraphemeBounds(
920 GetGraphemeIterator(),
921 run
->is_rtl
? intersection
.end() - 1 : intersection
.start()));
922 const Range rightmost_character_x
= RoundRangeF(run
->GetGraphemeBounds(
923 GetGraphemeIterator(),
924 run
->is_rtl
? intersection
.start() : intersection
.end() - 1));
925 Range
range_x(leftmost_character_x
.start(), rightmost_character_x
.end());
926 DCHECK(!range_x
.is_reversed());
927 if (range_x
.is_empty())
930 // Union this with the last range if they're adjacent.
931 DCHECK(bounds
.empty() || bounds
.back().GetMax() <= range_x
.GetMin());
932 if (!bounds
.empty() && bounds
.back().GetMax() == range_x
.GetMin()) {
933 range_x
= Range(bounds
.back().GetMin(), range_x
.GetMax());
936 bounds
.push_back(range_x
);
938 for (Range
& bound
: bounds
) {
939 std::vector
<Rect
> current_rects
= TextBoundsToViewBounds(bound
);
940 rects
.insert(rects
.end(), current_rects
.begin(), current_rects
.end());
945 size_t RenderTextHarfBuzz::TextIndexToDisplayIndex(size_t index
) {
946 return TextIndexToGivenTextIndex(GetDisplayText(), index
);
949 size_t RenderTextHarfBuzz::DisplayIndexToTextIndex(size_t index
) {
952 const size_t text_index
= UTF16OffsetToIndex(text(), 0, index
);
953 DCHECK_LE(text_index
, text().length());
957 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index
) {
958 if (index
== 0 || index
== text().length())
960 if (!IsValidLogicalIndex(index
))
962 base::i18n::BreakIterator
* grapheme_iterator
= GetGraphemeIterator();
963 return !grapheme_iterator
|| grapheme_iterator
->IsGraphemeBoundary(index
);
966 void RenderTextHarfBuzz::OnLayoutTextAttributeChanged(bool text_changed
) {
967 update_layout_run_list_
= true;
968 OnDisplayTextAttributeChanged();
971 void RenderTextHarfBuzz::OnDisplayTextAttributeChanged() {
972 update_display_text_
= true;
973 update_grapheme_iterator_
= true;
976 void RenderTextHarfBuzz::EnsureLayout() {
977 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
978 tracked_objects::ScopedTracker
tracking_profile(
979 FROM_HERE_WITH_EXPLICIT_FUNCTION(
980 "431326 RenderTextHarfBuzz::EnsureLayout"));
982 EnsureLayoutRunList();
984 if (update_display_run_list_
) {
985 DCHECK(text_elided());
986 const base::string16
& display_text
= GetDisplayText();
987 display_run_list_
.reset(new internal::TextRunList
);
989 if (!display_text
.empty()) {
990 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayout1");
992 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
994 tracked_objects::ScopedTracker
tracking_profile1(
995 FROM_HERE_WITH_EXPLICIT_FUNCTION(
996 "431326 RenderTextHarfBuzz::EnsureLayout1"));
997 ItemizeTextToRuns(display_text
, display_run_list_
.get());
999 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
1001 tracked_objects::ScopedTracker
tracking_profile2(
1002 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1003 "431326 RenderTextHarfBuzz::EnsureLayout12"));
1004 ShapeRunList(display_text
, display_run_list_
.get());
1006 update_display_run_list_
= false;
1008 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
1010 tracked_objects::ScopedTracker
tracking_profile14(
1011 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1012 "431326 RenderTextHarfBuzz::EnsureLayout14"));
1013 std::vector
<internal::Line
> empty_lines
;
1014 set_lines(&empty_lines
);
1017 if (lines().empty()) {
1018 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1019 tracked_objects::ScopedTracker
tracking_profile2(
1020 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1021 "431326 RenderTextHarfBuzz::EnsureLayout2"));
1023 internal::TextRunList
* run_list
= GetRunList();
1024 HarfBuzzLineBreaker
line_breaker(
1025 display_rect().width(), font_list().GetBaseline(),
1026 std::max(font_list().GetHeight(), min_line_height()), multiline(),
1027 word_wrap_behavior(), GetDisplayText(),
1028 multiline() ? &GetLineBreaks() : nullptr, *run_list
);
1030 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1031 tracked_objects::ScopedTracker
tracking_profile3(
1032 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1033 "431326 RenderTextHarfBuzz::EnsureLayout3"));
1035 for (size_t i
= 0; i
< run_list
->size(); ++i
)
1036 line_breaker
.AddRun(i
);
1037 std::vector
<internal::Line
> lines
;
1038 line_breaker
.Finalize(&lines
, &total_size_
);
1043 void RenderTextHarfBuzz::DrawVisualText(Canvas
* canvas
) {
1044 internal::SkiaTextRenderer
renderer(canvas
);
1045 DrawVisualTextInternal(&renderer
);
1048 void RenderTextHarfBuzz::DrawVisualTextInternal(
1049 internal::SkiaTextRenderer
* renderer
) {
1050 DCHECK(!update_layout_run_list_
);
1051 DCHECK(!update_display_run_list_
);
1052 DCHECK(!update_display_text_
);
1053 if (lines().empty())
1056 ApplyFadeEffects(renderer
);
1057 ApplyTextShadows(renderer
);
1058 ApplyCompositionAndSelectionStyles();
1060 internal::TextRunList
* run_list
= GetRunList();
1061 for (size_t i
= 0; i
< lines().size(); ++i
) {
1062 const internal::Line
& line
= lines()[i
];
1063 const Vector2d origin
= GetLineOffset(i
) + Vector2d(0, line
.baseline
);
1064 SkScalar preceding_segment_widths
= 0;
1065 for (const internal::LineSegment
& segment
: line
.segments
) {
1066 const internal::TextRunHarfBuzz
& run
= *run_list
->runs()[segment
.run
];
1067 renderer
->SetTypeface(run
.skia_face
.get());
1068 renderer
->SetTextSize(SkIntToScalar(run
.font_size
));
1069 renderer
->SetFontRenderParams(run
.render_params
,
1070 subpixel_rendering_suppressed());
1071 Range glyphs_range
= run
.CharRangeToGlyphRange(segment
.char_range
);
1072 scoped_ptr
<SkPoint
[]> positions(new SkPoint
[glyphs_range
.length()]);
1073 SkScalar offset_x
= preceding_segment_widths
-
1074 ((glyphs_range
.GetMin() != 0)
1075 ? run
.positions
[glyphs_range
.GetMin()].x()
1077 for (size_t j
= 0; j
< glyphs_range
.length(); ++j
) {
1078 positions
[j
] = run
.positions
[(glyphs_range
.is_reversed()) ?
1079 (glyphs_range
.start() - j
) :
1080 (glyphs_range
.start() + j
)];
1081 positions
[j
].offset(SkIntToScalar(origin
.x()) + offset_x
,
1082 SkIntToScalar(origin
.y() + run
.baseline_offset
));
1084 for (BreakList
<SkColor
>::const_iterator it
=
1085 colors().GetBreak(segment
.char_range
.start());
1086 it
!= colors().breaks().end() &&
1087 it
->first
< segment
.char_range
.end();
1089 const Range intersection
=
1090 colors().GetRange(it
).Intersect(segment
.char_range
);
1091 const Range colored_glyphs
= run
.CharRangeToGlyphRange(intersection
);
1092 // The range may be empty if a portion of a multi-character grapheme is
1093 // selected, yielding two colors for a single glyph. For now, this just
1094 // paints the glyph with a single style, but it should paint it twice,
1095 // clipped according to selection bounds. See http://crbug.com/366786
1096 if (colored_glyphs
.is_empty())
1099 renderer
->SetForegroundColor(it
->second
);
1100 renderer
->DrawPosText(
1101 &positions
[colored_glyphs
.start() - glyphs_range
.start()],
1102 &run
.glyphs
[colored_glyphs
.start()], colored_glyphs
.length());
1103 int start_x
= SkScalarRoundToInt(
1104 positions
[colored_glyphs
.start() - glyphs_range
.start()].x());
1105 int end_x
= SkScalarRoundToInt(
1106 (colored_glyphs
.end() == glyphs_range
.end())
1107 ? (SkFloatToScalar(segment
.width
) + preceding_segment_widths
+
1108 SkIntToScalar(origin
.x()))
1109 : positions
[colored_glyphs
.end() - glyphs_range
.start()].x());
1110 renderer
->DrawDecorations(start_x
, origin
.y(), end_x
- start_x
,
1111 run
.underline
, run
.strike
,
1112 run
.diagonal_strike
);
1114 preceding_segment_widths
+= SkFloatToScalar(segment
.width
);
1118 renderer
->EndDiagonalStrike();
1120 UndoCompositionAndSelectionStyles();
1123 size_t RenderTextHarfBuzz::GetRunContainingCaret(
1124 const SelectionModel
& caret
) {
1125 DCHECK(!update_display_run_list_
);
1126 size_t layout_position
= TextIndexToDisplayIndex(caret
.caret_pos());
1127 LogicalCursorDirection affinity
= caret
.caret_affinity();
1128 internal::TextRunList
* run_list
= GetRunList();
1129 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
1130 internal::TextRunHarfBuzz
* run
= run_list
->runs()[i
];
1131 if (RangeContainsCaret(run
->range
, layout_position
, affinity
))
1134 return run_list
->size();
1137 size_t RenderTextHarfBuzz::GetRunContainingXCoord(float x
,
1138 float* offset
) const {
1139 DCHECK(!update_display_run_list_
);
1140 const internal::TextRunList
* run_list
= GetRunList();
1142 return run_list
->size();
1143 // Find the text run containing the argument point (assumed already offset).
1144 float current_x
= 0;
1145 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
1146 size_t run
= run_list
->visual_to_logical(i
);
1147 current_x
+= run_list
->runs()[run
]->width
;
1148 if (x
< current_x
) {
1149 *offset
= x
- (current_x
- run_list
->runs()[run
]->width
);
1153 return run_list
->size();
1156 SelectionModel
RenderTextHarfBuzz::FirstSelectionModelInsideRun(
1157 const internal::TextRunHarfBuzz
* run
) {
1158 size_t position
= DisplayIndexToTextIndex(run
->range
.start());
1159 position
= IndexOfAdjacentGrapheme(position
, CURSOR_FORWARD
);
1160 return SelectionModel(position
, CURSOR_BACKWARD
);
1163 SelectionModel
RenderTextHarfBuzz::LastSelectionModelInsideRun(
1164 const internal::TextRunHarfBuzz
* run
) {
1165 size_t position
= DisplayIndexToTextIndex(run
->range
.end());
1166 position
= IndexOfAdjacentGrapheme(position
, CURSOR_BACKWARD
);
1167 return SelectionModel(position
, CURSOR_FORWARD
);
1170 void RenderTextHarfBuzz::ItemizeTextToRuns(
1171 const base::string16
& text
,
1172 internal::TextRunList
* run_list_out
) {
1173 const bool is_text_rtl
= GetTextDirection(text
) == base::i18n::RIGHT_TO_LEFT
;
1174 DCHECK_NE(0U, text
.length());
1176 // If ICU fails to itemize the text, we create a run that spans the entire
1177 // text. This is needed because leaving the runs set empty causes some clients
1178 // to misbehave since they expect non-zero text metrics from a non-empty text.
1179 base::i18n::BiDiLineIterator bidi_iterator
;
1180 if (!bidi_iterator
.Open(text
, is_text_rtl
, false)) {
1181 internal::TextRunHarfBuzz
* run
= new internal::TextRunHarfBuzz
;
1182 run
->range
= Range(0, text
.length());
1183 run_list_out
->add(run
);
1184 run_list_out
->InitIndexMap();
1188 // Temporarily apply composition underlines and selection colors.
1189 ApplyCompositionAndSelectionStyles();
1191 // Build the run list from the script items and ranged styles and baselines.
1192 // Use an empty color BreakList to avoid breaking runs at color boundaries.
1193 BreakList
<SkColor
> empty_colors
;
1194 empty_colors
.SetMax(text
.length());
1195 DCHECK_LE(text
.size(), baselines().max());
1196 for (const BreakList
<bool>& style
: styles())
1197 DCHECK_LE(text
.size(), style
.max());
1198 internal::StyleIterator
style(empty_colors
, baselines(), styles());
1200 for (size_t run_break
= 0; run_break
< text
.length();) {
1201 internal::TextRunHarfBuzz
* run
= new internal::TextRunHarfBuzz
;
1202 run
->range
.set_start(run_break
);
1203 run
->font_style
= (style
.style(BOLD
) ? Font::BOLD
: 0) |
1204 (style
.style(ITALIC
) ? Font::ITALIC
: 0);
1205 run
->baseline_type
= style
.baseline();
1206 run
->strike
= style
.style(STRIKE
);
1207 run
->diagonal_strike
= style
.style(DIAGONAL_STRIKE
);
1208 run
->underline
= style
.style(UNDERLINE
);
1209 int32 script_item_break
= 0;
1210 bidi_iterator
.GetLogicalRun(run_break
, &script_item_break
, &run
->level
);
1211 // Odd BiDi embedding levels correspond to RTL runs.
1212 run
->is_rtl
= (run
->level
% 2) == 1;
1213 // Find the length and script of this script run.
1214 script_item_break
= ScriptInterval(text
, run_break
,
1215 script_item_break
- run_break
, &run
->script
) + run_break
;
1217 // Find the next break and advance the iterators as needed.
1218 run_break
= std::min(
1219 static_cast<size_t>(script_item_break
),
1220 TextIndexToGivenTextIndex(text
, style
.GetRange().end()));
1222 // Break runs at certain characters that need to be rendered separately to
1223 // prevent either an unusual character from forcing a fallback font on the
1224 // entire run, or brackets from being affected by a fallback font.
1225 // http://crbug.com/278913, http://crbug.com/396776
1226 if (run_break
> run
->range
.start())
1227 run_break
= FindRunBreakingCharacter(text
, run
->range
.start(), run_break
);
1229 DCHECK(IsValidCodePointIndex(text
, run_break
));
1230 style
.UpdatePosition(DisplayIndexToTextIndex(run_break
));
1231 run
->range
.set_end(run_break
);
1233 run_list_out
->add(run
);
1236 // Undo the temporarily applied composition underlines and selection colors.
1237 UndoCompositionAndSelectionStyles();
1239 run_list_out
->InitIndexMap();
1242 bool RenderTextHarfBuzz::CompareFamily(
1243 const base::string16
& text
,
1244 const std::string
& family
,
1245 const gfx::FontRenderParams
& render_params
,
1246 internal::TextRunHarfBuzz
* run
,
1247 std::string
* best_family
,
1248 gfx::FontRenderParams
* best_render_params
,
1249 size_t* best_missing_glyphs
) {
1250 if (!ShapeRunWithFont(text
, family
, render_params
, run
))
1253 const size_t missing_glyphs
= run
->CountMissingGlyphs();
1254 if (missing_glyphs
< *best_missing_glyphs
) {
1255 *best_family
= family
;
1256 *best_render_params
= render_params
;
1257 *best_missing_glyphs
= missing_glyphs
;
1259 return missing_glyphs
== 0;
1262 void RenderTextHarfBuzz::ShapeRunList(const base::string16
& text
,
1263 internal::TextRunList
* run_list
) {
1264 for (auto* run
: run_list
->runs())
1265 ShapeRun(text
, run
);
1266 run_list
->ComputePrecedingRunWidths();
1269 void RenderTextHarfBuzz::ShapeRun(const base::string16
& text
,
1270 internal::TextRunHarfBuzz
* run
) {
1271 const Font
& primary_font
= font_list().GetPrimaryFont();
1272 const std::string primary_family
= primary_font
.GetFontName();
1273 run
->font_size
= primary_font
.GetFontSize();
1274 run
->baseline_offset
= 0;
1275 if (run
->baseline_type
!= NORMAL_BASELINE
) {
1276 // Calculate a slightly smaller font. The ratio here is somewhat arbitrary.
1277 // Proportions from 5/9 to 5/7 all look pretty good.
1278 const float ratio
= 5.0f
/ 9.0f
;
1279 run
->font_size
= gfx::ToRoundedInt(primary_font
.GetFontSize() * ratio
);
1280 switch (run
->baseline_type
) {
1282 run
->baseline_offset
=
1283 primary_font
.GetCapHeight() - primary_font
.GetHeight();
1286 run
->baseline_offset
=
1287 gfx::ToRoundedInt(primary_font
.GetCapHeight() * ratio
) -
1288 primary_font
.GetCapHeight();
1291 run
->baseline_offset
=
1292 primary_font
.GetHeight() - primary_font
.GetBaseline();
1294 case INFERIOR
: // Fall through.
1300 std::string best_family
;
1301 FontRenderParams best_render_params
;
1302 size_t best_missing_glyphs
= std::numeric_limits
<size_t>::max();
1304 for (const Font
& font
: font_list().GetFonts()) {
1305 if (CompareFamily(text
, font
.GetFontName(), font
.GetFontRenderParams(),
1306 run
, &best_family
, &best_render_params
,
1307 &best_missing_glyphs
))
1312 Font uniscribe_font
;
1313 std::string uniscribe_family
;
1314 const base::char16
* run_text
= &(text
[run
->range
.start()]);
1315 if (GetUniscribeFallbackFont(primary_font
, run_text
, run
->range
.length(),
1317 uniscribe_family
= uniscribe_font
.GetFontName();
1318 if (CompareFamily(text
, uniscribe_family
,
1319 uniscribe_font
.GetFontRenderParams(), run
,
1320 &best_family
, &best_render_params
, &best_missing_glyphs
))
1325 std::vector
<std::string
> fallback_families
=
1326 GetFallbackFontFamilies(primary_family
);
1329 // Append fonts in the fallback list of the Uniscribe font.
1330 if (!uniscribe_family
.empty()) {
1331 std::vector
<std::string
> uniscribe_fallbacks
=
1332 GetFallbackFontFamilies(uniscribe_family
);
1333 fallback_families
.insert(fallback_families
.end(),
1334 uniscribe_fallbacks
.begin(), uniscribe_fallbacks
.end());
1337 // Add Segoe UI and its associated linked fonts to the fallback font list to
1338 // ensure that the fallback list covers the basic cases.
1339 // http://crbug.com/467459. On some Windows configurations the default font
1340 // could be a raster font like System, which would not give us a reasonable
1341 // fallback font list.
1342 if (!LowerCaseEqualsASCII(primary_family
, "segoe ui") &&
1343 !LowerCaseEqualsASCII(uniscribe_family
, "segoe ui")) {
1344 std::vector
<std::string
> default_fallback_families
=
1345 GetFallbackFontFamilies("Segoe UI");
1346 fallback_families
.insert(fallback_families
.end(),
1347 default_fallback_families
.begin(), default_fallback_families
.end());
1351 // Use a set to track the fallback fonts and avoid duplicate entries.
1352 std::set
<std::string
, CaseInsensitiveCompare
> fallback_fonts
;
1354 // Try shaping with the fallback fonts.
1355 for (const auto& family
: fallback_families
) {
1356 if (family
== primary_family
)
1359 if (family
== uniscribe_family
)
1362 if (fallback_fonts
.find(family
) != fallback_fonts
.end())
1365 fallback_fonts
.insert(family
);
1367 FontRenderParamsQuery query
;
1368 query
.families
.push_back(family
);
1369 query
.pixel_size
= run
->font_size
;
1370 query
.style
= run
->font_style
;
1371 FontRenderParams fallback_render_params
= GetFontRenderParams(query
, NULL
);
1372 if (CompareFamily(text
, family
, fallback_render_params
, run
, &best_family
,
1373 &best_render_params
, &best_missing_glyphs
))
1377 if (!best_family
.empty() &&
1378 (best_family
== run
->family
||
1379 ShapeRunWithFont(text
, best_family
, best_render_params
, run
)))
1382 run
->glyph_count
= 0;
1386 bool RenderTextHarfBuzz::ShapeRunWithFont(const base::string16
& text
,
1387 const std::string
& font_family
,
1388 const FontRenderParams
& params
,
1389 internal::TextRunHarfBuzz
* run
) {
1390 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1391 tracked_objects::ScopedTracker
tracking_profile0(
1392 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1393 "431326 RenderTextHarfBuzz::ShapeRunWithFont0"));
1395 skia::RefPtr
<SkTypeface
> skia_face
=
1396 internal::CreateSkiaTypeface(font_family
, run
->font_style
);
1397 if (skia_face
== NULL
)
1399 run
->skia_face
= skia_face
;
1400 run
->family
= font_family
;
1401 run
->render_params
= params
;
1403 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1404 tracked_objects::ScopedTracker
tracking_profile01(
1405 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1406 "431326 RenderTextHarfBuzz::ShapeRunWithFont01"));
1408 hb_font_t
* harfbuzz_font
= CreateHarfBuzzFont(
1409 run
->skia_face
.get(), SkIntToScalar(run
->font_size
), run
->render_params
,
1410 subpixel_rendering_suppressed());
1412 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1413 tracked_objects::ScopedTracker
tracking_profile1(
1414 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1415 "431326 RenderTextHarfBuzz::ShapeRunWithFont1"));
1417 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
1418 // buffer holds our text, run information to be used by the shaping engine,
1419 // and the resulting glyph data.
1420 hb_buffer_t
* buffer
= hb_buffer_create();
1422 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1423 tracked_objects::ScopedTracker
tracking_profile1q(
1424 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1425 "431326 RenderTextHarfBuzz::ShapeRunWithFont11"));
1427 hb_buffer_add_utf16(buffer
, reinterpret_cast<const uint16
*>(text
.c_str()),
1428 text
.length(), run
->range
.start(), run
->range
.length());
1430 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1431 tracked_objects::ScopedTracker
tracking_profile12(
1432 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1433 "431326 RenderTextHarfBuzz::ShapeRunWithFont12"));
1435 hb_buffer_set_script(buffer
, ICUScriptToHBScript(run
->script
));
1437 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1438 tracked_objects::ScopedTracker
tracking_profile13(
1439 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1440 "431326 RenderTextHarfBuzz::ShapeRunWithFont13"));
1442 hb_buffer_set_direction(buffer
,
1443 run
->is_rtl
? HB_DIRECTION_RTL
: HB_DIRECTION_LTR
);
1445 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1446 tracked_objects::ScopedTracker
tracking_profile14(
1447 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1448 "431326 RenderTextHarfBuzz::ShapeRunWithFont14"));
1450 // TODO(ckocagil): Should we determine the actual language?
1451 hb_buffer_set_language(buffer
, hb_language_get_default());
1453 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1454 tracked_objects::ScopedTracker
tracking_profile15(
1455 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1456 "431326 RenderTextHarfBuzz::ShapeRunWithFont15"));
1459 hb_shape(harfbuzz_font
, buffer
, NULL
, 0);
1461 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1462 tracked_objects::ScopedTracker
tracking_profile2(
1463 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1464 "431326 RenderTextHarfBuzz::ShapeRunWithFont2"));
1466 // Populate the run fields with the resulting glyph data in the buffer.
1467 unsigned int glyph_count
= 0;
1468 hb_glyph_info_t
* infos
= hb_buffer_get_glyph_infos(buffer
, &glyph_count
);
1469 run
->glyph_count
= glyph_count
;
1470 hb_glyph_position_t
* hb_positions
=
1471 hb_buffer_get_glyph_positions(buffer
, NULL
);
1472 run
->glyphs
.reset(new uint16
[run
->glyph_count
]);
1473 run
->glyph_to_char
.resize(run
->glyph_count
);
1474 run
->positions
.reset(new SkPoint
[run
->glyph_count
]);
1477 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1478 tracked_objects::ScopedTracker
tracking_profile3(
1479 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1480 "431326 RenderTextHarfBuzz::ShapeRunWithFont3"));
1482 for (size_t i
= 0; i
< run
->glyph_count
; ++i
) {
1483 DCHECK_LE(infos
[i
].codepoint
, std::numeric_limits
<uint16
>::max());
1484 run
->glyphs
[i
] = static_cast<uint16
>(infos
[i
].codepoint
);
1485 run
->glyph_to_char
[i
] = infos
[i
].cluster
;
1486 const SkScalar x_offset
= SkFixedToScalar(hb_positions
[i
].x_offset
);
1487 const SkScalar y_offset
= SkFixedToScalar(hb_positions
[i
].y_offset
);
1488 run
->positions
[i
].set(run
->width
+ x_offset
, -y_offset
);
1489 run
->width
+= (glyph_width_for_test_
> 0)
1490 ? glyph_width_for_test_
1491 : SkFixedToFloat(hb_positions
[i
].x_advance
);
1492 // Round run widths if subpixel positioning is off to match native behavior.
1493 if (!run
->render_params
.subpixel_positioning
)
1494 run
->width
= std::floor(run
->width
+ 0.5f
);
1497 hb_buffer_destroy(buffer
);
1498 hb_font_destroy(harfbuzz_font
);
1502 void RenderTextHarfBuzz::EnsureLayoutRunList() {
1503 if (update_layout_run_list_
) {
1504 layout_run_list_
.Reset();
1506 const base::string16
& text
= layout_text();
1507 if (!text
.empty()) {
1508 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayoutRunList");
1509 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
1511 tracked_objects::ScopedTracker
tracking_profile1(
1512 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1513 "431326 RenderTextHarfBuzz::EnsureLayout1"));
1514 ItemizeTextToRuns(text
, &layout_run_list_
);
1516 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
1518 tracked_objects::ScopedTracker
tracking_profile2(
1519 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1520 "431326 RenderTextHarfBuzz::EnsureLayout12"));
1521 ShapeRunList(text
, &layout_run_list_
);
1524 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
1526 tracked_objects::ScopedTracker
tracking_profile14(
1527 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1528 "431326 RenderTextHarfBuzz::EnsureLayout14"));
1530 std::vector
<internal::Line
> empty_lines
;
1531 set_lines(&empty_lines
);
1532 display_run_list_
.reset();
1533 update_display_text_
= true;
1534 update_layout_run_list_
= false;
1536 if (update_display_text_
) {
1537 UpdateDisplayText(multiline() ? 0 : layout_run_list_
.width());
1538 update_display_text_
= false;
1539 update_display_run_list_
= text_elided();
1543 base::i18n::BreakIterator
* RenderTextHarfBuzz::GetGraphemeIterator() {
1544 if (update_grapheme_iterator_
) {
1545 update_grapheme_iterator_
= false;
1546 grapheme_iterator_
.reset(new base::i18n::BreakIterator(
1548 base::i18n::BreakIterator::BREAK_CHARACTER
));
1549 if (!grapheme_iterator_
->Init())
1550 grapheme_iterator_
.reset();
1552 return grapheme_iterator_
.get();
1555 internal::TextRunList
* RenderTextHarfBuzz::GetRunList() {
1556 DCHECK(!update_layout_run_list_
);
1557 DCHECK(!update_display_run_list_
);
1558 return text_elided() ? display_run_list_
.get() : &layout_run_list_
;
1561 const internal::TextRunList
* RenderTextHarfBuzz::GetRunList() const {
1562 return const_cast<RenderTextHarfBuzz
*>(this)->GetRunList();