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