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
);
663 return ((glyph_range
.end() == glyph_count
)
664 ? SkFloatToScalar(width
)
665 : positions
[glyph_range
.end()].x()) -
666 positions
[glyph_range
.start()].x();
669 TextRunList::TextRunList() : width_(0.0f
) {}
671 TextRunList::~TextRunList() {}
673 void TextRunList::Reset() {
678 void TextRunList::InitIndexMap() {
679 if (runs_
.size() == 1) {
680 visual_to_logical_
= logical_to_visual_
= std::vector
<int32_t>(1, 0);
683 const size_t num_runs
= runs_
.size();
684 std::vector
<UBiDiLevel
> levels(num_runs
);
685 for (size_t i
= 0; i
< num_runs
; ++i
)
686 levels
[i
] = runs_
[i
]->level
;
687 visual_to_logical_
.resize(num_runs
);
688 ubidi_reorderVisual(&levels
[0], num_runs
, &visual_to_logical_
[0]);
689 logical_to_visual_
.resize(num_runs
);
690 ubidi_reorderLogical(&levels
[0], num_runs
, &logical_to_visual_
[0]);
693 void TextRunList::ComputePrecedingRunWidths() {
694 // Precalculate run width information.
696 for (size_t i
= 0; i
< runs_
.size(); ++i
) {
697 TextRunHarfBuzz
* run
= runs_
[visual_to_logical_
[i
]];
698 run
->preceding_run_widths
= width_
;
699 width_
+= run
->width
;
703 size_t TextRunList::GetRunIndexAt(size_t position
) const {
704 for (size_t i
= 0; i
< runs_
.size(); ++i
) {
705 if (runs_
[i
]->range
.start() <= position
&& runs_
[i
]->range
.end() > position
)
711 } // namespace internal
713 RenderTextHarfBuzz::RenderTextHarfBuzz()
715 update_layout_run_list_(false),
716 update_display_run_list_(false),
717 update_grapheme_iterator_(false),
718 update_display_text_(false),
719 glyph_width_for_test_(0u) {
720 set_truncate_length(kMaxTextLength
);
723 RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
725 scoped_ptr
<RenderText
> RenderTextHarfBuzz::CreateInstanceOfSameType() const {
726 return make_scoped_ptr(new RenderTextHarfBuzz
);
729 bool RenderTextHarfBuzz::MultilineSupported() const {
733 const base::string16
& RenderTextHarfBuzz::GetDisplayText() {
734 // TODO(oshima): Consider supporting eliding multi-line text.
735 // This requires max_line support first.
737 elide_behavior() == NO_ELIDE
||
738 elide_behavior() == FADE_TAIL
) {
739 // Call UpdateDisplayText to clear |display_text_| and |text_elided_|
740 // on the RenderText class.
741 UpdateDisplayText(0);
742 update_display_text_
= false;
743 display_run_list_
.reset();
744 return layout_text();
747 EnsureLayoutRunList();
748 DCHECK(!update_display_text_
);
749 return text_elided() ? display_text() : layout_text();
752 Size
RenderTextHarfBuzz::GetStringSize() {
753 const SizeF size_f
= GetStringSizeF();
754 return Size(std::ceil(size_f
.width()), size_f
.height());
757 SizeF
RenderTextHarfBuzz::GetStringSizeF() {
762 SelectionModel
RenderTextHarfBuzz::FindCursorPosition(const Point
& point
) {
765 int x
= ToTextPoint(point
).x();
767 size_t run_index
= GetRunContainingXCoord(x
, &offset
);
769 internal::TextRunList
* run_list
= GetRunList();
770 if (run_index
>= run_list
->size())
771 return EdgeSelectionModel((x
< 0) ? CURSOR_LEFT
: CURSOR_RIGHT
);
772 const internal::TextRunHarfBuzz
& run
= *run_list
->runs()[run_index
];
773 for (size_t i
= 0; i
< run
.glyph_count
; ++i
) {
775 i
+ 1 == run
.glyph_count
? run
.width
: run
.positions
[i
+ 1].x();
776 const SkScalar middle
= (end
+ run
.positions
[i
].x()) / 2;
778 if (offset
< middle
) {
779 return SelectionModel(DisplayIndexToTextIndex(
780 run
.glyph_to_char
[i
] + (run
.is_rtl
? 1 : 0)),
781 (run
.is_rtl
? CURSOR_BACKWARD
: CURSOR_FORWARD
));
784 return SelectionModel(DisplayIndexToTextIndex(
785 run
.glyph_to_char
[i
] + (run
.is_rtl
? 0 : 1)),
786 (run
.is_rtl
? CURSOR_FORWARD
: CURSOR_BACKWARD
));
789 return EdgeSelectionModel(CURSOR_RIGHT
);
792 std::vector
<RenderText::FontSpan
> RenderTextHarfBuzz::GetFontSpansForTesting() {
795 internal::TextRunList
* run_list
= GetRunList();
796 std::vector
<RenderText::FontSpan
> spans
;
797 for (auto* run
: run_list
->runs()) {
798 SkString family_name
;
799 run
->skia_face
->getFamilyName(&family_name
);
800 Font
font(family_name
.c_str(), run
->font_size
);
801 spans
.push_back(RenderText::FontSpan(
803 Range(DisplayIndexToTextIndex(run
->range
.start()),
804 DisplayIndexToTextIndex(run
->range
.end()))));
810 Range
RenderTextHarfBuzz::GetGlyphBounds(size_t index
) {
812 const size_t run_index
=
813 GetRunContainingCaret(SelectionModel(index
, CURSOR_FORWARD
));
814 internal::TextRunList
* run_list
= GetRunList();
815 // Return edge bounds if the index is invalid or beyond the layout text size.
816 if (run_index
>= run_list
->size())
817 return Range(GetStringSize().width());
818 const size_t layout_index
= TextIndexToDisplayIndex(index
);
819 internal::TextRunHarfBuzz
* run
= run_list
->runs()[run_index
];
821 run
->GetGraphemeBounds(GetGraphemeIterator(), layout_index
);
822 // If cursor is enabled, extend the last glyph up to the rightmost cursor
823 // position since clients expect them to be contiguous.
824 if (cursor_enabled() && run_index
== run_list
->size() - 1 &&
825 index
== (run
->is_rtl
? run
->range
.start() : run
->range
.end() - 1))
826 bounds
.set_end(std::ceil(bounds
.end()));
827 return run
->is_rtl
? RangeF(bounds
.end(), bounds
.start()).Round()
831 int RenderTextHarfBuzz::GetDisplayTextBaseline() {
833 return lines()[0].baseline
;
836 SelectionModel
RenderTextHarfBuzz::AdjacentCharSelectionModel(
837 const SelectionModel
& selection
,
838 VisualCursorDirection direction
) {
839 DCHECK(!update_display_run_list_
);
841 internal::TextRunList
* run_list
= GetRunList();
842 internal::TextRunHarfBuzz
* run
;
844 size_t run_index
= GetRunContainingCaret(selection
);
845 if (run_index
>= run_list
->size()) {
846 // The cursor is not in any run: we're at the visual and logical edge.
847 SelectionModel edge
= EdgeSelectionModel(direction
);
848 if (edge
.caret_pos() == selection
.caret_pos())
850 int visual_index
= (direction
== CURSOR_RIGHT
) ? 0 : run_list
->size() - 1;
851 run
= run_list
->runs()[run_list
->visual_to_logical(visual_index
)];
853 // If the cursor is moving within the current run, just move it by one
854 // grapheme in the appropriate direction.
855 run
= run_list
->runs()[run_index
];
856 size_t caret
= selection
.caret_pos();
857 bool forward_motion
= run
->is_rtl
== (direction
== CURSOR_LEFT
);
858 if (forward_motion
) {
859 if (caret
< DisplayIndexToTextIndex(run
->range
.end())) {
860 caret
= IndexOfAdjacentGrapheme(caret
, CURSOR_FORWARD
);
861 return SelectionModel(caret
, CURSOR_BACKWARD
);
864 if (caret
> DisplayIndexToTextIndex(run
->range
.start())) {
865 caret
= IndexOfAdjacentGrapheme(caret
, CURSOR_BACKWARD
);
866 return SelectionModel(caret
, CURSOR_FORWARD
);
869 // The cursor is at the edge of a run; move to the visually adjacent run.
870 int visual_index
= run_list
->logical_to_visual(run_index
);
871 visual_index
+= (direction
== CURSOR_LEFT
) ? -1 : 1;
872 if (visual_index
< 0 || visual_index
>= static_cast<int>(run_list
->size()))
873 return EdgeSelectionModel(direction
);
874 run
= run_list
->runs()[run_list
->visual_to_logical(visual_index
)];
876 bool forward_motion
= run
->is_rtl
== (direction
== CURSOR_LEFT
);
877 return forward_motion
? FirstSelectionModelInsideRun(run
) :
878 LastSelectionModelInsideRun(run
);
881 SelectionModel
RenderTextHarfBuzz::AdjacentWordSelectionModel(
882 const SelectionModel
& selection
,
883 VisualCursorDirection direction
) {
885 return EdgeSelectionModel(direction
);
887 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
888 bool success
= iter
.Init();
893 // Match OS specific word break behavior.
896 if (direction
== CURSOR_RIGHT
) {
897 pos
= std::min(selection
.caret_pos() + 1, text().length());
898 while (iter
.Advance()) {
900 if (iter
.IsWord() && pos
> selection
.caret_pos())
903 } else { // direction == CURSOR_LEFT
904 // Notes: We always iterate words from the beginning.
905 // This is probably fast enough for our usage, but we may
906 // want to modify WordIterator so that it can start from the
907 // middle of string and advance backwards.
908 pos
= std::max
<int>(selection
.caret_pos() - 1, 0);
909 while (iter
.Advance()) {
911 size_t begin
= iter
.pos() - iter
.GetString().length();
912 if (begin
== selection
.caret_pos()) {
913 // The cursor is at the beginning of a word.
914 // Move to previous word.
916 } else if (iter
.pos() >= selection
.caret_pos()) {
917 // The cursor is in the middle or at the end of a word.
918 // Move to the top of current word.
922 pos
= iter
.pos() - iter
.GetString().length();
926 return SelectionModel(pos
, CURSOR_FORWARD
);
928 internal::TextRunList
* run_list
= GetRunList();
929 SelectionModel
cur(selection
);
931 cur
= AdjacentCharSelectionModel(cur
, direction
);
932 size_t run
= GetRunContainingCaret(cur
);
933 if (run
== run_list
->size())
935 const bool is_forward
=
936 run_list
->runs()[run
]->is_rtl
== (direction
== CURSOR_LEFT
);
937 size_t cursor
= cur
.caret_pos();
938 if (is_forward
? iter
.IsEndOfWord(cursor
) : iter
.IsStartOfWord(cursor
))
945 std::vector
<Rect
> RenderTextHarfBuzz::GetSubstringBounds(const Range
& range
) {
946 DCHECK(!update_display_run_list_
);
947 DCHECK(Range(0, text().length()).Contains(range
));
948 Range
layout_range(TextIndexToDisplayIndex(range
.start()),
949 TextIndexToDisplayIndex(range
.end()));
950 DCHECK(Range(0, GetDisplayText().length()).Contains(layout_range
));
952 std::vector
<Rect
> rects
;
953 if (layout_range
.is_empty())
955 std::vector
<Range
> bounds
;
957 internal::TextRunList
* run_list
= GetRunList();
959 // Add a Range for each run/selection intersection.
960 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
961 internal::TextRunHarfBuzz
* run
=
962 run_list
->runs()[run_list
->visual_to_logical(i
)];
963 Range intersection
= run
->range
.Intersect(layout_range
);
964 if (!intersection
.IsValid())
966 DCHECK(!intersection
.is_reversed());
967 const size_t left_index
=
968 run
->is_rtl
? intersection
.end() - 1 : intersection
.start();
969 const Range leftmost_character_x
=
970 run
->GetGraphemeBounds(GetGraphemeIterator(), left_index
).Round();
971 const size_t right_index
=
972 run
->is_rtl
? intersection
.start() : intersection
.end() - 1;
973 const Range rightmost_character_x
=
974 run
->GetGraphemeBounds(GetGraphemeIterator(), right_index
).Round();
975 Range
range_x(leftmost_character_x
.start(), rightmost_character_x
.end());
976 DCHECK(!range_x
.is_reversed());
977 if (range_x
.is_empty())
980 // Union this with the last range if they're adjacent.
981 DCHECK(bounds
.empty() || bounds
.back().GetMax() <= range_x
.GetMin());
982 if (!bounds
.empty() && bounds
.back().GetMax() == range_x
.GetMin()) {
983 range_x
= Range(bounds
.back().GetMin(), range_x
.GetMax());
986 bounds
.push_back(range_x
);
988 for (Range
& bound
: bounds
) {
989 std::vector
<Rect
> current_rects
= TextBoundsToViewBounds(bound
);
990 rects
.insert(rects
.end(), current_rects
.begin(), current_rects
.end());
995 size_t RenderTextHarfBuzz::TextIndexToDisplayIndex(size_t index
) {
996 return TextIndexToGivenTextIndex(GetDisplayText(), index
);
999 size_t RenderTextHarfBuzz::DisplayIndexToTextIndex(size_t index
) {
1002 const size_t text_index
= UTF16OffsetToIndex(text(), 0, index
);
1003 DCHECK_LE(text_index
, text().length());
1007 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index
) {
1008 if (index
== 0 || index
== text().length())
1010 if (!IsValidLogicalIndex(index
))
1012 base::i18n::BreakIterator
* grapheme_iterator
= GetGraphemeIterator();
1013 return !grapheme_iterator
|| grapheme_iterator
->IsGraphemeBoundary(index
);
1016 void RenderTextHarfBuzz::OnLayoutTextAttributeChanged(bool text_changed
) {
1017 update_layout_run_list_
= true;
1018 OnDisplayTextAttributeChanged();
1021 void RenderTextHarfBuzz::OnDisplayTextAttributeChanged() {
1022 update_display_text_
= true;
1023 update_grapheme_iterator_
= true;
1026 void RenderTextHarfBuzz::EnsureLayout() {
1027 EnsureLayoutRunList();
1029 if (update_display_run_list_
) {
1030 DCHECK(text_elided());
1031 const base::string16
& display_text
= GetDisplayText();
1032 display_run_list_
.reset(new internal::TextRunList
);
1034 if (!display_text
.empty()) {
1035 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayout1");
1037 ItemizeTextToRuns(display_text
, display_run_list_
.get());
1039 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1041 tracked_objects::ScopedTracker
tracking_profile(
1042 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 1"));
1043 ShapeRunList(display_text
, display_run_list_
.get());
1045 update_display_run_list_
= false;
1047 std::vector
<internal::Line
> empty_lines
;
1048 set_lines(&empty_lines
);
1051 if (lines().empty()) {
1052 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1054 scoped_ptr
<tracked_objects::ScopedTracker
> tracking_profile(
1055 new tracked_objects::ScopedTracker(
1056 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 HarfBuzzLineBreaker")));
1058 internal::TextRunList
* run_list
= GetRunList();
1059 HarfBuzzLineBreaker
line_breaker(
1060 display_rect().width(), font_list().GetBaseline(),
1061 std::max(font_list().GetHeight(), min_line_height()),
1062 word_wrap_behavior(), GetDisplayText(),
1063 multiline() ? &GetLineBreaks() : nullptr, *run_list
);
1065 tracking_profile
.reset();
1068 line_breaker
.ConstructMultiLines();
1070 line_breaker
.ConstructSingleLine();
1071 std::vector
<internal::Line
> lines
;
1072 line_breaker
.FinalizeLines(&lines
, &total_size_
);
1077 void RenderTextHarfBuzz::DrawVisualText(Canvas
* canvas
) {
1078 internal::SkiaTextRenderer
renderer(canvas
);
1079 DrawVisualTextInternal(&renderer
);
1082 void RenderTextHarfBuzz::DrawVisualTextInternal(
1083 internal::SkiaTextRenderer
* renderer
) {
1084 DCHECK(!update_layout_run_list_
);
1085 DCHECK(!update_display_run_list_
);
1086 DCHECK(!update_display_text_
);
1087 if (lines().empty())
1090 ApplyFadeEffects(renderer
);
1091 ApplyTextShadows(renderer
);
1092 ApplyCompositionAndSelectionStyles();
1094 internal::TextRunList
* run_list
= GetRunList();
1095 for (size_t i
= 0; i
< lines().size(); ++i
) {
1096 const internal::Line
& line
= lines()[i
];
1097 const Vector2d origin
= GetLineOffset(i
) + Vector2d(0, line
.baseline
);
1098 SkScalar preceding_segment_widths
= 0;
1099 for (const internal::LineSegment
& segment
: line
.segments
) {
1100 const internal::TextRunHarfBuzz
& run
= *run_list
->runs()[segment
.run
];
1101 renderer
->SetTypeface(run
.skia_face
.get());
1102 renderer
->SetTextSize(SkIntToScalar(run
.font_size
));
1103 renderer
->SetFontRenderParams(run
.render_params
,
1104 subpixel_rendering_suppressed());
1105 Range glyphs_range
= run
.CharRangeToGlyphRange(segment
.char_range
);
1106 scoped_ptr
<SkPoint
[]> positions(new SkPoint
[glyphs_range
.length()]);
1107 SkScalar offset_x
= preceding_segment_widths
-
1108 ((glyphs_range
.GetMin() != 0)
1109 ? run
.positions
[glyphs_range
.GetMin()].x()
1111 for (size_t j
= 0; j
< glyphs_range
.length(); ++j
) {
1112 positions
[j
] = run
.positions
[(glyphs_range
.is_reversed()) ?
1113 (glyphs_range
.start() - j
) :
1114 (glyphs_range
.start() + j
)];
1115 positions
[j
].offset(SkIntToScalar(origin
.x()) + offset_x
,
1116 SkIntToScalar(origin
.y() + run
.baseline_offset
));
1118 for (BreakList
<SkColor
>::const_iterator it
=
1119 colors().GetBreak(segment
.char_range
.start());
1120 it
!= colors().breaks().end() &&
1121 it
->first
< segment
.char_range
.end();
1123 const Range intersection
=
1124 colors().GetRange(it
).Intersect(segment
.char_range
);
1125 const Range colored_glyphs
= run
.CharRangeToGlyphRange(intersection
);
1126 // The range may be empty if a portion of a multi-character grapheme is
1127 // selected, yielding two colors for a single glyph. For now, this just
1128 // paints the glyph with a single style, but it should paint it twice,
1129 // clipped according to selection bounds. See http://crbug.com/366786
1130 if (colored_glyphs
.is_empty())
1133 renderer
->SetForegroundColor(it
->second
);
1134 renderer
->DrawPosText(
1135 &positions
[colored_glyphs
.start() - glyphs_range
.start()],
1136 &run
.glyphs
[colored_glyphs
.start()], colored_glyphs
.length());
1137 int start_x
= SkScalarRoundToInt(
1138 positions
[colored_glyphs
.start() - glyphs_range
.start()].x());
1139 int end_x
= SkScalarRoundToInt(
1140 (colored_glyphs
.end() == glyphs_range
.end())
1141 ? (SkFloatToScalar(segment
.width()) + preceding_segment_widths
+
1142 SkIntToScalar(origin
.x()))
1143 : positions
[colored_glyphs
.end() - glyphs_range
.start()].x());
1144 renderer
->DrawDecorations(start_x
, origin
.y(), end_x
- start_x
,
1145 run
.underline
, run
.strike
,
1146 run
.diagonal_strike
);
1148 preceding_segment_widths
+= SkFloatToScalar(segment
.width());
1152 renderer
->EndDiagonalStrike();
1154 UndoCompositionAndSelectionStyles();
1157 size_t RenderTextHarfBuzz::GetRunContainingCaret(
1158 const SelectionModel
& caret
) {
1159 DCHECK(!update_display_run_list_
);
1160 size_t layout_position
= TextIndexToDisplayIndex(caret
.caret_pos());
1161 LogicalCursorDirection affinity
= caret
.caret_affinity();
1162 internal::TextRunList
* run_list
= GetRunList();
1163 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
1164 internal::TextRunHarfBuzz
* run
= run_list
->runs()[i
];
1165 if (RangeContainsCaret(run
->range
, layout_position
, affinity
))
1168 return run_list
->size();
1171 size_t RenderTextHarfBuzz::GetRunContainingXCoord(float x
,
1172 float* offset
) const {
1173 DCHECK(!update_display_run_list_
);
1174 const internal::TextRunList
* run_list
= GetRunList();
1176 return run_list
->size();
1177 // Find the text run containing the argument point (assumed already offset).
1178 float current_x
= 0;
1179 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
1180 size_t run
= run_list
->visual_to_logical(i
);
1181 current_x
+= run_list
->runs()[run
]->width
;
1182 if (x
< current_x
) {
1183 *offset
= x
- (current_x
- run_list
->runs()[run
]->width
);
1187 return run_list
->size();
1190 SelectionModel
RenderTextHarfBuzz::FirstSelectionModelInsideRun(
1191 const internal::TextRunHarfBuzz
* run
) {
1192 size_t position
= DisplayIndexToTextIndex(run
->range
.start());
1193 position
= IndexOfAdjacentGrapheme(position
, CURSOR_FORWARD
);
1194 return SelectionModel(position
, CURSOR_BACKWARD
);
1197 SelectionModel
RenderTextHarfBuzz::LastSelectionModelInsideRun(
1198 const internal::TextRunHarfBuzz
* run
) {
1199 size_t position
= DisplayIndexToTextIndex(run
->range
.end());
1200 position
= IndexOfAdjacentGrapheme(position
, CURSOR_BACKWARD
);
1201 return SelectionModel(position
, CURSOR_FORWARD
);
1204 void RenderTextHarfBuzz::ItemizeTextToRuns(
1205 const base::string16
& text
,
1206 internal::TextRunList
* run_list_out
) {
1207 DCHECK_NE(0U, text
.length());
1209 // If ICU fails to itemize the text, we create a run that spans the entire
1210 // text. This is needed because leaving the runs set empty causes some clients
1211 // to misbehave since they expect non-zero text metrics from a non-empty text.
1212 base::i18n::BiDiLineIterator bidi_iterator
;
1213 if (!bidi_iterator
.Open(text
, GetTextDirection(text
))) {
1214 internal::TextRunHarfBuzz
* run
= new internal::TextRunHarfBuzz
;
1215 run
->range
= Range(0, text
.length());
1216 run_list_out
->add(run
);
1217 run_list_out
->InitIndexMap();
1221 // Temporarily apply composition underlines and selection colors.
1222 ApplyCompositionAndSelectionStyles();
1224 // Build the run list from the script items and ranged styles and baselines.
1225 // Use an empty color BreakList to avoid breaking runs at color boundaries.
1226 BreakList
<SkColor
> empty_colors
;
1227 empty_colors
.SetMax(text
.length());
1228 DCHECK_LE(text
.size(), baselines().max());
1229 for (const BreakList
<bool>& style
: styles())
1230 DCHECK_LE(text
.size(), style
.max());
1231 internal::StyleIterator
style(empty_colors
, baselines(), styles());
1233 for (size_t run_break
= 0; run_break
< text
.length();) {
1234 internal::TextRunHarfBuzz
* run
= new internal::TextRunHarfBuzz
;
1235 run
->range
.set_start(run_break
);
1236 run
->font_style
= (style
.style(BOLD
) ? Font::BOLD
: 0) |
1237 (style
.style(ITALIC
) ? Font::ITALIC
: 0);
1238 run
->baseline_type
= style
.baseline();
1239 run
->strike
= style
.style(STRIKE
);
1240 run
->diagonal_strike
= style
.style(DIAGONAL_STRIKE
);
1241 run
->underline
= style
.style(UNDERLINE
);
1242 int32 script_item_break
= 0;
1243 bidi_iterator
.GetLogicalRun(run_break
, &script_item_break
, &run
->level
);
1244 // Odd BiDi embedding levels correspond to RTL runs.
1245 run
->is_rtl
= (run
->level
% 2) == 1;
1246 // Find the length and script of this script run.
1247 script_item_break
= ScriptInterval(text
, run_break
,
1248 script_item_break
- run_break
, &run
->script
) + run_break
;
1250 // Find the next break and advance the iterators as needed.
1251 run_break
= std::min(
1252 static_cast<size_t>(script_item_break
),
1253 TextIndexToGivenTextIndex(text
, style
.GetRange().end()));
1255 // Break runs at certain characters that need to be rendered separately to
1256 // prevent either an unusual character from forcing a fallback font on the
1257 // entire run, or brackets from being affected by a fallback font.
1258 // http://crbug.com/278913, http://crbug.com/396776
1259 if (run_break
> run
->range
.start())
1260 run_break
= FindRunBreakingCharacter(text
, run
->range
.start(), run_break
);
1262 DCHECK(IsValidCodePointIndex(text
, run_break
));
1263 style
.UpdatePosition(DisplayIndexToTextIndex(run_break
));
1264 run
->range
.set_end(run_break
);
1266 run_list_out
->add(run
);
1269 // Undo the temporarily applied composition underlines and selection colors.
1270 UndoCompositionAndSelectionStyles();
1272 run_list_out
->InitIndexMap();
1275 bool RenderTextHarfBuzz::CompareFamily(
1276 const base::string16
& text
,
1277 const std::string
& family
,
1278 const gfx::FontRenderParams
& render_params
,
1279 internal::TextRunHarfBuzz
* run
,
1280 std::string
* best_family
,
1281 gfx::FontRenderParams
* best_render_params
,
1282 size_t* best_missing_glyphs
) {
1283 if (!ShapeRunWithFont(text
, family
, render_params
, run
))
1286 const size_t missing_glyphs
= run
->CountMissingGlyphs();
1287 if (missing_glyphs
< *best_missing_glyphs
) {
1288 *best_family
= family
;
1289 *best_render_params
= render_params
;
1290 *best_missing_glyphs
= missing_glyphs
;
1292 return missing_glyphs
== 0;
1295 void RenderTextHarfBuzz::ShapeRunList(const base::string16
& text
,
1296 internal::TextRunList
* run_list
) {
1297 for (auto* run
: run_list
->runs())
1298 ShapeRun(text
, run
);
1299 run_list
->ComputePrecedingRunWidths();
1302 void RenderTextHarfBuzz::ShapeRun(const base::string16
& text
,
1303 internal::TextRunHarfBuzz
* run
) {
1304 const Font
& primary_font
= font_list().GetPrimaryFont();
1305 const std::string primary_family
= primary_font
.GetFontName();
1306 run
->font_size
= primary_font
.GetFontSize();
1307 run
->baseline_offset
= 0;
1308 if (run
->baseline_type
!= NORMAL_BASELINE
) {
1309 // Calculate a slightly smaller font. The ratio here is somewhat arbitrary.
1310 // Proportions from 5/9 to 5/7 all look pretty good.
1311 const float ratio
= 5.0f
/ 9.0f
;
1312 run
->font_size
= gfx::ToRoundedInt(primary_font
.GetFontSize() * ratio
);
1313 switch (run
->baseline_type
) {
1315 run
->baseline_offset
=
1316 primary_font
.GetCapHeight() - primary_font
.GetHeight();
1319 run
->baseline_offset
=
1320 gfx::ToRoundedInt(primary_font
.GetCapHeight() * ratio
) -
1321 primary_font
.GetCapHeight();
1324 run
->baseline_offset
=
1325 primary_font
.GetHeight() - primary_font
.GetBaseline();
1327 case INFERIOR
: // Fall through.
1333 std::string best_family
;
1334 FontRenderParams best_render_params
;
1335 size_t best_missing_glyphs
= std::numeric_limits
<size_t>::max();
1337 for (const Font
& font
: font_list().GetFonts()) {
1338 if (CompareFamily(text
, font
.GetFontName(), font
.GetFontRenderParams(),
1339 run
, &best_family
, &best_render_params
,
1340 &best_missing_glyphs
))
1345 Font uniscribe_font
;
1346 std::string uniscribe_family
;
1347 const base::char16
* run_text
= &(text
[run
->range
.start()]);
1348 if (GetUniscribeFallbackFont(primary_font
, run_text
, run
->range
.length(),
1350 uniscribe_family
= uniscribe_font
.GetFontName();
1351 if (CompareFamily(text
, uniscribe_family
,
1352 uniscribe_font
.GetFontRenderParams(), run
,
1353 &best_family
, &best_render_params
, &best_missing_glyphs
))
1358 std::vector
<std::string
> fallback_families
=
1359 GetFallbackFontFamilies(primary_family
);
1362 // Append fonts in the fallback list of the Uniscribe font.
1363 if (!uniscribe_family
.empty()) {
1364 std::vector
<std::string
> uniscribe_fallbacks
=
1365 GetFallbackFontFamilies(uniscribe_family
);
1366 fallback_families
.insert(fallback_families
.end(),
1367 uniscribe_fallbacks
.begin(), uniscribe_fallbacks
.end());
1370 // Add Segoe UI and its associated linked fonts to the fallback font list to
1371 // ensure that the fallback list covers the basic cases.
1372 // http://crbug.com/467459. On some Windows configurations the default font
1373 // could be a raster font like System, which would not give us a reasonable
1374 // fallback font list.
1375 if (!base::LowerCaseEqualsASCII(primary_family
, "segoe ui") &&
1376 !base::LowerCaseEqualsASCII(uniscribe_family
, "segoe ui")) {
1377 std::vector
<std::string
> default_fallback_families
=
1378 GetFallbackFontFamilies("Segoe UI");
1379 fallback_families
.insert(fallback_families
.end(),
1380 default_fallback_families
.begin(), default_fallback_families
.end());
1384 // Use a set to track the fallback fonts and avoid duplicate entries.
1385 std::set
<std::string
, CaseInsensitiveCompare
> fallback_fonts
;
1387 // Try shaping with the fallback fonts.
1388 for (const auto& family
: fallback_families
) {
1389 if (family
== primary_family
)
1392 if (family
== uniscribe_family
)
1395 if (fallback_fonts
.find(family
) != fallback_fonts
.end())
1398 fallback_fonts
.insert(family
);
1400 FontRenderParamsQuery query
;
1401 query
.families
.push_back(family
);
1402 query
.pixel_size
= run
->font_size
;
1403 query
.style
= run
->font_style
;
1404 FontRenderParams fallback_render_params
= GetFontRenderParams(query
, NULL
);
1405 if (CompareFamily(text
, family
, fallback_render_params
, run
, &best_family
,
1406 &best_render_params
, &best_missing_glyphs
))
1410 if (!best_family
.empty() &&
1411 (best_family
== run
->family
||
1412 ShapeRunWithFont(text
, best_family
, best_render_params
, run
)))
1415 run
->glyph_count
= 0;
1419 bool RenderTextHarfBuzz::ShapeRunWithFont(const base::string16
& text
,
1420 const std::string
& font_family
,
1421 const FontRenderParams
& params
,
1422 internal::TextRunHarfBuzz
* run
) {
1423 skia::RefPtr
<SkTypeface
> skia_face
=
1424 internal::CreateSkiaTypeface(font_family
, run
->font_style
);
1425 if (skia_face
== NULL
)
1427 run
->skia_face
= skia_face
;
1428 run
->family
= font_family
;
1429 run
->render_params
= params
;
1431 hb_font_t
* harfbuzz_font
= CreateHarfBuzzFont(
1432 run
->skia_face
.get(), SkIntToScalar(run
->font_size
), run
->render_params
,
1433 subpixel_rendering_suppressed());
1435 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
1436 // buffer holds our text, run information to be used by the shaping engine,
1437 // and the resulting glyph data.
1438 hb_buffer_t
* buffer
= hb_buffer_create();
1439 hb_buffer_add_utf16(buffer
, reinterpret_cast<const uint16
*>(text
.c_str()),
1440 text
.length(), run
->range
.start(), run
->range
.length());
1441 hb_buffer_set_script(buffer
, ICUScriptToHBScript(run
->script
));
1442 hb_buffer_set_direction(buffer
,
1443 run
->is_rtl
? HB_DIRECTION_RTL
: HB_DIRECTION_LTR
);
1444 // TODO(ckocagil): Should we determine the actual language?
1445 hb_buffer_set_language(buffer
, hb_language_get_default());
1448 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1450 tracked_objects::ScopedTracker
tracking_profile(
1451 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 hb_shape()"));
1454 hb_shape(harfbuzz_font
, buffer
, NULL
, 0);
1457 // Populate the run fields with the resulting glyph data in the buffer.
1458 unsigned int glyph_count
= 0;
1459 hb_glyph_info_t
* infos
= hb_buffer_get_glyph_infos(buffer
, &glyph_count
);
1460 run
->glyph_count
= glyph_count
;
1461 hb_glyph_position_t
* hb_positions
=
1462 hb_buffer_get_glyph_positions(buffer
, NULL
);
1463 run
->glyphs
.reset(new uint16
[run
->glyph_count
]);
1464 run
->glyph_to_char
.resize(run
->glyph_count
);
1465 run
->positions
.reset(new SkPoint
[run
->glyph_count
]);
1468 for (size_t i
= 0; i
< run
->glyph_count
; ++i
) {
1469 DCHECK_LE(infos
[i
].codepoint
, std::numeric_limits
<uint16
>::max());
1470 run
->glyphs
[i
] = static_cast<uint16
>(infos
[i
].codepoint
);
1471 run
->glyph_to_char
[i
] = infos
[i
].cluster
;
1472 const SkScalar x_offset
= SkFixedToScalar(hb_positions
[i
].x_offset
);
1473 const SkScalar y_offset
= SkFixedToScalar(hb_positions
[i
].y_offset
);
1474 run
->positions
[i
].set(run
->width
+ x_offset
, -y_offset
);
1475 run
->width
+= (glyph_width_for_test_
> 0)
1476 ? glyph_width_for_test_
1477 : SkFixedToFloat(hb_positions
[i
].x_advance
);
1478 // Round run widths if subpixel positioning is off to match native behavior.
1479 if (!run
->render_params
.subpixel_positioning
)
1480 run
->width
= std::floor(run
->width
+ 0.5f
);
1483 hb_buffer_destroy(buffer
);
1484 hb_font_destroy(harfbuzz_font
);
1488 void RenderTextHarfBuzz::EnsureLayoutRunList() {
1489 if (update_layout_run_list_
) {
1490 layout_run_list_
.Reset();
1492 const base::string16
& text
= layout_text();
1493 if (!text
.empty()) {
1494 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayoutRunList");
1495 ItemizeTextToRuns(text
, &layout_run_list_
);
1497 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1499 tracked_objects::ScopedTracker
tracking_profile(
1500 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 2"));
1501 ShapeRunList(text
, &layout_run_list_
);
1504 std::vector
<internal::Line
> empty_lines
;
1505 set_lines(&empty_lines
);
1506 display_run_list_
.reset();
1507 update_display_text_
= true;
1508 update_layout_run_list_
= false;
1510 if (update_display_text_
) {
1511 UpdateDisplayText(multiline() ? 0 : layout_run_list_
.width());
1512 update_display_text_
= false;
1513 update_display_run_list_
= text_elided();
1517 base::i18n::BreakIterator
* RenderTextHarfBuzz::GetGraphemeIterator() {
1518 if (update_grapheme_iterator_
) {
1519 update_grapheme_iterator_
= false;
1520 grapheme_iterator_
.reset(new base::i18n::BreakIterator(
1522 base::i18n::BreakIterator::BREAK_CHARACTER
));
1523 if (!grapheme_iterator_
->Init())
1524 grapheme_iterator_
.reset();
1526 return grapheme_iterator_
.get();
1529 internal::TextRunList
* RenderTextHarfBuzz::GetRunList() {
1530 DCHECK(!update_layout_run_list_
);
1531 DCHECK(!update_display_run_list_
);
1532 return text_elided() ? display_run_list_
.get() : &layout_run_list_
;
1535 const internal::TextRunList
* RenderTextHarfBuzz::GetRunList() const {
1536 return const_cast<RenderTextHarfBuzz
*>(this)->GetRunList();