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